phpjsonquery-stringmagic-quotes

convert JSON object to query string and then back to an object


I know this has been asked a few times but please bear with me.

I have a google maps object which is rather complex (it contains various nodes, coordinates, etc) and I am trying to pass it as a query string.

I need a play javascript/jQuery solution.

I have tried the .param method which gives a jQuery error. The only thing that works is the "stringify" method which then creates a string that when appearing as a url looks a bit like this: %7B%5C"shape_1%5C"%3A%7B%5C"color%5C"%3A%5C"%237F0000%5C"%2C%5C"data%5C"%3A%7B%5C"b%5C"%3A%5B%7B%5C"Na%5C"%3A51.56727431757122%2C%5C"Oa%5C"%3A-0.10462402858888709%7D%2C....

php translates that as: {\\"shape_1\\":{\\"color\\":\\"#7F0000\\",\\"data\\":{\\"b\\":[{\\"Na\\":51.56727431757122,\\"Oa\\":-0.10462402858888709},...

but having said that I don't want to use PHP, I am just showing you what it does in case it helps you see what stringify did to the object.

After I unescape with Javascript it looks a bit more normal like:

{\"shape_1\":{\"color\":\"#7F0000\",\"data\":{\"b\":[{\"Na\":51.56727431757122,\"Oa\":-0.10462402858888709},..

So as you can see, the unescaped sequence has these slashes everywhere. When I try to evaluate that into a JSON object I get "Illegal token \". The parse method also fails. I just can't find any way to put this string back into the complex JSON object that it was. I have looked online for various suggestions but they fail. I also don't understand why stringify injects all these slashes which simply shouldn't be there. If anyone has an idea how to take that object, put it in a query string and then parse it back I would be very grateful.

Nick


Update: The answer is this:

encodeURIComponent(JSON.stringify(myObject));

And then on the receiving end:

var a = querySt("data");
var b = decodeURIComponent(a);
var c = unescape(b);
var d = JSON.parse(c);

or all in one line

JSON.parse(unescape(decodeURIComponent(querySt("data"))));

Nick


Solution

  • See http://php.net/manual/de/security.magicquotes.php - you have to turn off magic quotes. They are old, deprecated stuff, they are insecure and break stuff.

    Magic Quotes is a process that automagically escapes incoming data to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed.

    Howto: http://www.php.net/manual/de/security.magicquotes.disabling.php