Home > Back-end >  How to format the invalid JSON to a proper JSON format in PHP?
How to format the invalid JSON to a proper JSON format in PHP?

Time:12-29

The below json string creating an issue while doing json_decode(). While removing the spaces, slashes, \n, it is working. Can someone suggest?

  {\n   \"long_format\":{\n      \"date\":\"DD/MM/YYYY\",\n      \"time\":\"H:mm:ss\",\n      \"date_time\":\"DD/MM/YYYY H:mm:ss\"\n   },\n   \"short_format\":{\n      \"date\":\"DD/MM/YY\",\n      \"time\":\"hh:mm:ss A\",\n      \"date_time\":\"DD/MM/YY hh:mm:ss A\"\n   }\n}

CodePudding user response:

You can use preg_replace()

$string = preg_replace(array('/\\\\n\s /m','/\\\\n/m','/\\\\"/m'), array('','','"'), $string);
print_r(json_decode($string,true));

Output: https://3v4l.org/GQhTO

Note: Its better to correct the source code which created this json data, in case you have control over that.

  • Related