I have a JS literal object string such as {name:{first:"George",middle:"William"},surname:"Washington"}
and I have to convert it in Json. How can I do it using PHP?
-
possible duplicate of How to parse a JSON string using PHPSergiu Paraschiv– Sergiu Paraschiv2013年09月19日 15:09:53 +00:00Commented Sep 19, 2013 at 15:09
-
2That's kind of strange having a string of a js object literal in php.Musa– Musa2013年09月19日 15:11:26 +00:00Commented Sep 19, 2013 at 15:11
-
possible duplicate of how to decode this JSON string?epascarello– epascarello2013年09月19日 15:11:29 +00:00Commented Sep 19, 2013 at 15:11
-
4This is not a duplicate question. JSON and object literals are not the same thing and json_decode doesn't parse object literal strings.Aristona– Aristona2014年12月17日 22:53:56 +00:00Commented Dec 17, 2014 at 22:53
-
because the key names are not quoted in the JS literal string, this could get ugly. I suspect you'll have to write your own parser similar to the JS runtime interpreter's parser, which is a complex and buggy proposition. Perhaps you can simplify the grammar to accept only a subset of JS object literals, which would make it possible to do the job with a reasonable set of regexps?RobP– RobP2015年02月25日 17:33:49 +00:00Commented Feb 25, 2015 at 17:33
4 Answers 4
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);
Comments
JS:
// Pretend we're POSTing this
var 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
Comments
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.
1 Comment
Not json_encode, use $var = json_decode($_POST['names'], true)
. You can then use it like echo $var['surname']
to echo "Washington".
1 Comment
Explore related questions
See similar questions with these tags.