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?

4
  • 8
    That service is not providing valid JSON. Commented Mar 26, 2012 at 23:33
  • 2
    this is invalid JSON... test it on jsonlint Commented Mar 26, 2012 at 23:35
  • I think the OP is aware it's invalid. The OP is looking for a way to handle this particular case. Commented Mar 26, 2012 at 23:39
  • 1
    This was answered here (I believe it answers your question): Invalid JSON parsing using PHP Commented Mar 26, 2012 at 23:40

1 Answer 1

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'];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.