0

I'm trying to save a string which is encoded as json into another json string.
In particular, I have to be able to handle empty objects: "{}".

PHP:

$sVal = "{}";
$jsonString  = "{\"Var2\":\"My first var\", \"Var2\":\"My second var\", \"MyBlankObject\":\"{}\"}"

...

Javascript:

var oMyJSON = JSON.parse('< ?= $jsonString;? >');

I get a JSON parse error saying an unexpected { was found.

I can see the code in Chrome's debugger.

The brackets are simply removed and in the client side (javascript ) code, the object is replaced with the word null. That's not valid JSON.

,"Properties":null,

This causes javascript to crash.

If I try to json_encode it on the server side (PHP) I get double quotes on each side of the brackets.

,"Properties":""{}"",

I get the same thing if I just add the double quotes: ""{}""

Of course, this causes javascript to crash too.

Once in the client and I have the JSON object intact, I need to be able to extract the 'string' held in the property: MyBlankObject and then decode that JSON into a seperate JSON object.

Everything I've tried fails. How can I accomplish this?

3
  • PHP is for hypertext, not script, You'll need to echo $jsonString somewhere in your html first. Then you can access that with javascript. Also, you shouldn't have to escape the double quotes. As is, you don't have valid JSON. Commented Dec 2, 2018 at 17:42
  • Hmm, according to JSONlint that is valid, as a string. To comment on your second issue, putting quotes around {} makes it a string rather than an object. I think you want something like this {"Var1":"My first var","Var2":"My second var","MyBlankObject":{}} Commented Dec 2, 2018 at 18:00
  • 1
    Never build your JSON string "manually" like you do with $jsonString = . It is bad practice. Always build your objects in the language you are using (PHP), and then use the built-in functions (json_encode) to build JSON. Commented Dec 19, 2018 at 20:49

1 Answer 1

3

You can define the object using PHP notation, and let json_encode encode it for you.

$phpArray = [
    'Var2' => 'My first var',
    'Var2' => 'My second var',
    'MyBlankObject' => new \stdClass
];

And then in the JavaScript:

var oMyJSON = JSON.parse('<?= json_encode($phpArray); ?>');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.