我有无效的外部 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
}
Run Code Online (Sandbox Code Playgroud)
正如你看到的很多名称,如 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
}
Run Code Online (Sandbox Code Playgroud)
请建议我一些 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));
Run Code Online (Sandbox Code Playgroud)
由于上面的例子不适用于真实数据(作战计划很少能在与敌人的第一次接触后幸存下来),这是我的第二个想法:
$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));
Run Code Online (Sandbox Code Playgroud)
但由于 google 在 RSS feed 中提供了这些数据,如果它适合您的用例,我建议您使用该数据,这只是为了好玩(-:
| 归档时间: |
|
| 查看次数: |
3573 次 |
| 最近记录: |