Jsp Jsp - 1 year ago 108
JSON Question

Convert Json Javascript format to PHP readable format

I have bunch of json files to read through and store some information to db using PHP.

The problem is these json keys are without quotes like:


PHP doesn't recognize it as json. However, if I take this json file and run it in a browser with javascript function "JSON.stringify" the data is formatted with quotes which can be used in PHP.

So I wrote a script to parse these files using javascript and then post it to PHP script to write it to the server. Works well in the browser BUT I cannot automate this as curl does not run javascript!!!

Is there anyway to convert json format (without quotes) to PHP readable format? I tried this suggestion... regex option did not work and I do not know how to work with PEAR, even though my server has PEAR Version: 1.10.1 and PHP Version: 5.4.45

Answer Source

Here is my solution to your problem. Yeah it is regex but it works.

$text = preg_replace(["/\\\\'/", '/(\{|,|\[\t|\n|\s)([a-zA-z0-9-_]+):/i'], ["'", '$1"$2":'], $text);
$text = json_decode($text);

$text - is the bad formatted json

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download