javascript tutorial - [Solved-5 Solutions] Safely turning a JSON string into an object - javascript - java script - javascript array
Problem :
How to Safely turning a JSON string into an object ?
Solution 1:
can do this unsafely with something like
var obj = eval("(" + json + ')');
click below button to copy the code. By JavaScript tutorial team
but that leaves us vulnerable to the json string containing other code, which it seems very dangerous to simply eval.
Solution 2:
JSON.parse(jsonString);
click below button to copy the code. By JavaScript tutorial team
Is a pure JavaScript approach so long as you can require a reasonably modern browser.
Solution 3:
The jQuery method is now deprecated. Use this method instead:
let jsonObject = JSON.parse(jsonString);
click below button to copy the code. By JavaScript tutorial team
Solution 4:
Use simple code represented in the following link on MSDN .
var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
click below button to copy the code. By JavaScript tutorial team
and reverse
var str = JSON.stringify(arr);
click below button to copy the code. By JavaScript tutorial team
Solution 5:
new Ajax.Request('/some_url', {
method:'get',
requestHeaders: {Accept: 'application/json'},
onSuccess: function(transport){
var json = transport.responseText.evalJSON(true);
}
});
click below button to copy the code. By JavaScript tutorial team
Calling evalJSON() with true as the argument sanitizes the incoming string.