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?
echo $jsonStringsomewhere 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.{}makes it a string rather than an object. I think you want something like this{"Var1":"My first var","Var2":"My second var","MyBlankObject":{}}$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.