gpt4 book ai didi

PHP 使用 json_decode() 读取无效的 json;

转载 作者:行者123 更新时间:2023-12-03 02:10:34 27 4
gpt4 key购买 nike

我有无效的外部 json 数据,名称周围没有双引号。

示例:

{
data: [
{
idx: 0,
id: "0",
url: "http://247wallst.com/",
a: [
{
t: "Title",
u: "http://247wallst.com/2012/07/30/",
sp: "About"
}
],
doc_id: "9386093612452939480"
},
{
idx: 1,
id: "-1"
}
],
results_per_page: 10,
total_number_of_news: 76,
news_per_month: [20, 0, 8, 1, 1, 2, 0, 2, 1, 0, 0, 1, 1, 0, 5, 1, 1, 1, 0, 2, 5, 16, 7, 1],
result_start_num: 2,
result_end_num: 2,
result_total_articles: 76
}

正如你看到的很多名称,如 data、idx、id、url 等都没有用双引号括起来,所以这使得这个 json 无效。如何使这个外部 json 有效?我已经尝试过 str_replace,将 '{' 替换为 '{"',将 ':' 替换为 '":',在未加引号的名称周围添加双引号,但这会弄乱一些已经用双引号引起来的变量。

如何使此 json 有效,以便我可以使用 PHP json_decode 读取此数据?我对 preg_replace 不太熟悉..

有效的 json 看起来像:

{
"data": [
{
"idx": 0,
"id": "0",
"url": "http://247wallst.com/",
"a": [
{
"t": "Title",
"u": "http://247wallst.com/2012/07/30/",
"sp": "About"
}
],
"doc_id": "9386093612452939480"
},
{
"idx": 1,
"id": "-1"
}
],
"results_per_page": 10,
"total_number_of_news": 76,
"news_per_month": [20, 0, 8, 1, 1, 2, 0, 2, 1, 0, 0, 1, 1, 0, 5, 1, 1, 1, 0, 2, 5, 16, 7, 1],
"result_start_num": 2,
"result_end_num": 2,
"result_total_articles": 76
}

请给我推荐一些 php preg_replace 函数。

数据来源: http://www.google.com/finance/company_news?q=aapl&output=json&start=1&num=1

最佳答案

使用 preg_replace 您可以执行以下操作:

json_decode(preg_replace('#(?<pre>\{|\[|,)\s*(?<key>(?:\w|_)+)\s*:#im', '$1"$2":', $in));

由于上面的例子不适用于真实数据(作战计划很少能在与敌人的第一次接触中幸存下来),这是我的第二个想法:

$infile = 'http://www.google.com/finance/company_news?q=aapl&output=json&start=1&num=1';

// first, get rid of the \x26 and other encoded bytes.
$in = preg_replace_callback('/\\\x([0-9A-F]{2})/i',
function($match){
return chr(intval($match[1], 16));
}, file_get_contents($infile));

$out = $in;

// find key candidates
preg_match_all('#(?<=\{|\[|,)\s*(?<key>(?:\w|_)+?)\s*:#im', $in, $m, PREG_OFFSET_CAPTURE);

$replaces_so_far = 0;
// check each candidate if its in a quoted string or not
foreach ($m['key'] as $match) {
$position = $match[1] + ($replaces_so_far * 2); // every time you expand one key, offsets need to be shifted with 2 (for the two " chars)
$key = $match[0];
$quotes_before = preg_match_all('/(?<!\\\)"/', substr($out, 0, $position), $m2);
if ($quotes_before % 2) { // not even number of not-escaped quotes, we are in quotes, ignore candidate
continue;
}
$out = substr_replace($out, '"'.$key.'"', $position, strlen($key));
++$replaces_so_far;
}

var_export(json_decode($out, true));

但是由于 google 在 RSS feed 中提供了这些数据,如果它适合您的用例,我建议您使用该数据,这只是为了好玩(-:

关于PHP 使用 json_decode() 读取无效的 json;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11729051/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com