1

I have an issue with parsing JSON data by json_decode PHP function. The issue is that the JSON I receive is not properly formatted. It looks as follows:

"{ user:1 ,product:4 ,commentCount: 1 ,comment:'All fine! Well done.' ,commentDate:{ year:2015 ,month:8 ,day:19 } , likes:8 }"

When I try to decode this string with json_decode PHP function I get NULL. Is it possible to properly format this string with a preg_replace function

EDIT: I found this code on the web but it only wraps the variable names in the quotes. The values are still as they were and json_decode still returns NULL.

// fix variable names
$PHPJSON = preg_replace( '/([a-zA-Z0-9_]+?):/' , '"$1":', $PHPJSON );
6
  • This is a not a valid json Commented Aug 19, 2015 at 14:29
  • Yes, I know. The question is if it is possible to format it correctly with the use of preg_replace? Commented Aug 19, 2015 at 14:34
  • Format it correctly where you create it in Javascript Commented Aug 19, 2015 at 14:35
  • I do not create it. I receive it from a third party. I am not able to change it before receiving. Commented Aug 19, 2015 at 14:36
  • Thats what I expected, you should at least tell them of their error though, maybe they will fix it Commented Aug 19, 2015 at 14:37

1 Answer 1

1

Working solution for your malformed json:

$json = "{ user:1 ,product:4 ,commentCount: 1 ,comment:'All fine! Well done.' ,commentDate:{ year:2015 ,month:8 ,day:19 } , likes:8 }";

$json = preg_replace('/(,|\{)[ \t\n]*(\w+)[ ]*:[ ]*/','$1"$2":',$json);
$json = preg_replace('/":\'?([^\[\]\{\}]*?)\'?[ \n\t]*(,"|\}$|\]$|\}\]|\]\}|\}|\])/','":"$1"$2',$json);

var_dump($json);

var_dump(json_decode($json));

But in general you need to wrap object param in double quotes "arg":1. Non-numeric values also. Just like this:

var_dump(json_decode('{"user":1}'));
var_dump(json_last_error());

The second function returns you id of an error, if there was any. Check the php manual for error codes identification

Sign up to request clarification or add additional context in comments.

6 Comments

He knows it is not well formed JSON, this is not an answer
Updated my answer with solution
Thats nice -1 removed
Thanks but I have already checked the PHP manual. The issue still persists though - the JSON is still wrongly formatted.
Do you used preg_replace's from my answer? On PHP 5.4 works just fine.
|

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.