You could also use eval()
but JSON.parse()
is safer and easier way, so why would you?
good and works
var yourJsonObject = JSON.parse(json_as_text);
I don't see any reason why would you prefer to use eval
. It only puts your application at risk.
That said - this is also possible.
bad - but also works
var yourJsonObject = eval(json_as_text);
Why is eval
a bad idea?
Consider the following example.
Some third party or user provided JSON string data.
var json = `
[{
"adjacencies": [
{
"nodeTo": function(){
return "delete server files - you have been hacked!";
}(),
"nodeFrom": "graphnode1",
"data": {
"$color": "#557EAA"
}
}
],
"data": {
"$color": "#EBB056",
"$type": "triangle",
"$dim": 9
},
"id": "graphnode1",
"name": "graphnode1"
},{
"adjacencies": [],
"data": {
"$color": "#EBB056",
"$type": "triangle",
"$dim": 9
},
"id": "graphnode2",
"name": "graphnode2"
}]
`;
Your server-side script processes that data.
Using JSON.parse
:
window.onload = function(){
var placeholder = document.getElementById('placeholder1');
placeholder.innerHTML = JSON.parse(json)[0].adjacencies[0].nodeTo;
}
will throw:
Uncaught SyntaxError: Unexpected token u in JSON at position X.
Function will not get executed.
You are safe.
Using eval()
:
window.onload = function(){
var placeholder = document.getElementById('placeholder1');
placeholder.innerHTML = eval(json)[0].adjacencies[0].nodeTo;
}
will execute the function and return the text.
If you run this on the serwer side and I replace this harmless function with one, that removes files from your website folder or does something harmful, then your app will get hacked. No errors/warnings will get thrown in this example.
You are NOT safe.
I was able to manipulate a JSON text string so it acts as a function which will execute on the server.
eval(JSON)[0].adjacencies[0].nodeTo
expects to process a JSON string but, in reality, we just executed a function on our server.
This could also be prevented if we server-side check all user-provided data before passing it to an eval()
function but why not just use the built-in tool for parsing JSON and avoid all this trouble and danger?