4

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?

Jeffrey
  • 4,098
  • 11
  • 42
  • 66
  • 8
    That service is not providing valid JSON. – alex Mar 26 '12 at 23:33
  • 2
    this is invalid JSON... test it on [jsonlint](http://jsonlint.com) – poncha Mar 26 '12 at 23:35
  • I think the OP is aware it's invalid. The OP is looking for a way to handle this particular case. – MitMaro Mar 26 '12 at 23:39
  • 1
    This was answered here (I believe it answers your question): [Invalid JSON parsing using PHP](http://stackoverflow.com/questions/1575198/invalid-json-parsing-using-php) – Mizuho Mar 26 '12 at 23:40

1 Answers1

3

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'];
Rifat
  • 7,628
  • 4
  • 32
  • 46