最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how to convert a JavaScript literal object into Json object in PHP - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Sep 19, 2013 at 15:08 tictic 4,19915 gold badges51 silver badges87 bronze badges 7
  • possible duplicate of How to parse a JSON string using PHP – Sergiu Paraschiv Commented Sep 19, 2013 at 15:09
  • 2 That's kind of strange having a string of a js object literal in php. – Musa Commented Sep 19, 2013 at 15:11
  • possible duplicate of how to decode this JSON string? – epascarello Commented Sep 19, 2013 at 15:11
  • 3 This is not a duplicate question. JSON and object literals are not the same thing and json_decode doesn't parse object literal strings. – Aristona Commented 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 plex 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 Commented Feb 25, 2015 at 17:33
 |  Show 2 more ments

4 Answers 4

Reset to default 5

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 poser

poser require ovidigital/js-object-to-json

2) Use it inside your project

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

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./watch?v=pORFYsgOXog

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.

Not json_encode, use $var = json_decode($_POST['names'], true). You can then use it like echo $var['surname'] to echo "Washington".

发布评论

评论列表(0)

  1. 暂无评论