简体   繁体   English

PHP为json_decode的数组添加引号

[英]PHP add quotes to array for json_decode

I'm looking to json_decode a string, but running into a problem with the array elements not having quotes. 我正在寻找json_decode一个字符串,但遇到了没有引号的数组元素的问题。

JSON JSON

{"Status":"DISPUTED","GUID":[]}
{"Status":"CONFIRMED","GUID":[G018712, G017623]}

PHP PHP

$json = '{"Status":"CONFIRMED","GUID":[G018712,G017623]}';
$a = json_decode($json, true);
print $a['Status'];

Results 结果

The php print above won't display anything because there are letters mixed in with the numerics within the array and the json_decode doesn't like it. 上面的php打印不会显示任何内容,因为数字中的数字与字母混合在一起,而json_decode不喜欢它。 How would you add strings to each array item, so that json_decode will work? 如何为每个数组项添加字符串,以便json_decode可以工作?

Your json is invalid. 你的json无效。 It should be - 它应该是 -

$json = '{"Status":"CONFIRMED","GUID":["G018712","G017623"]}';

or 要么

$json = '{Status:"CONFIRMED",GUID:["G018712","G017623"]}';

You can easily fix it using- 您可以使用以下方式轻松修复它

$json = preg_replace('/(?<!")(?<!\w)(\w+)(?!")(?!\w)/', '"$1"', $json);

Full example 完整的例子

$json = '{"Status":"CONFIRMED","GUID":[G018712,G017623]}{"Status":"CONFIRMED","GUID":[018712,a017623]}';
// fix json
$json = preg_replace('/(?<!")(?<!\w)(\w+)(?!")(?!\w)/', '"$1"', $json);
$a = json_decode($json, true);
print $a['Status'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM