PHP add quotes to array for json_decode

﹥>﹥吖頭↗ 提交于 2019-12-06 04:41:01

问题


I'm looking to json_decode a string, but running into a problem with the array elements not having quotes.

JSON

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

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. How would you add strings to each array item, so that json_decode will work?


回答1:


Your json is invalid. 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'];


来源:https://stackoverflow.com/questions/9881369/php-add-quotes-to-array-for-json-decode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!