-->

PHP add quotes to array for json_decode

2019-04-10 04:13发布

问题:

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'];