Given a string of JSON data, how can you safely turn that string into a JavaScript object?
Obviously you can do this unsafely with something like...
var obj = eval("(" + json + ')');
...but that leaves us vulnerable to the json string containing other code, which it seems very dangerous to simply eval.
JSON parsing is always pain in ass. If the input is not as expected it throws an error and crashes what you are doing. You can use the following tiny function to safely parse your input. It always turns an object even if the input is not valid or is already an object which is better for most cases.
Try this.This one is written in typescript.
JSON.parse(jsonString)
is a pure JavaScript approach so long as you can guarantee a reasonably modern browser.If your JavaScript are in Mootools the
JSON.parse
will be Anonymous by the Framework.A valid syntax to safely turning a JSON string into an object shall be:
Moreover a
JSON Request
is can raise an object that able to parse directly.You may cek how it turn a json raw data here:
http://jsfiddle.net/chetabahana/qbx9b5pm/
I'm not sure about other ways to do it but here's how you do it in Prototype (JSON tutorial).
Calling evalJSON() with true as the argument sanitizes the incoming string.
Try using the method with this Data object. ex:
Data='{result:true,count:1}
'This method really helps in Nodejs when you are working with serial port programming