how to convert a JavaScript literal object into Json object in PHP how to convert a JavaScript literal object into Json object in PHP json json

how to convert a JavaScript literal object into Json object in PHP


JS:

// Pretend we're POSTing thisvar foo = {foo:{first:"George",middle:"William"}};

PHP:

$foo = $_POST['foo'];$foo = json_decode( stripslashes( $foo ) );echo $foo->first;

Credit where credit is due: https://www.youtube.com/watch?v=pORFYsgOXog


If someone is still looking for an easy solution to this, as I did recently, you could check out the PHP library that I wrote: ovidigital/js-object-to-json

1) Install with composer

composer require ovidigital/js-object-to-json

2) Use it inside your project

$json = \OviDigital\JsObjectToJson\JsConverter::convertToJson($javascriptObjectString);


If you are lucky enough to know what the keys will be when they arrive on your script, and you know that they won't appear within the values, you could do this with str_replace() to add double quotes to the keys:

$notQuiteJson = '{name:{first:"George",middle:"William"},surname:"Washington"}';$initialJson = array('name:','first:','middle:','surname:');$replacedJson = array('"name":','"first":','"middle":','"surname":');$convertedDataString = str_replace($initialJson, $replacedJson, $notQuiteJson);$actualJson = json_decode($convertedDataString);

Far from perfect, but hopefully this helps someone.