Instead of using eval()
, a safer and easier alternative is to utilize JSON.parse()
. The latter eliminates risks associated with the former.
A good and effective method
var yourJsonObject = JSON.parse(json_as_text);
There is no apparent reason to resort to eval()
, as it compromises the security of your application.
This approach, however, remains viable.
An option that works but poses risks
var yourJsonObject = eval(json_as_text);
Why should you steer clear of eval
?
Let's consider the following scenario.
Data from a third party or user in the form of a JSON string.
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 this data.
Using JSON.parse
:
window.onload = function(){
var placeholder = document.getElementById('placeholder1');
placeholder.innerHTML = JSON.parse(json)[0].adjacencies[0].nodeTo;
}
will result in:
Uncaught SyntaxError: Unexpected token u in JSON at position X.
The function will not be executed.
You are protected.
Using eval()
:
window.onload = function(){
var placeholder = document.getElementById('placeholder1');
placeholder.innerHTML = eval(json)[0].adjacencies[0].nodeTo;
}
The function will be executed, potentially causing harm without any warnings.
If a malicious function replaces the harmless one, a breach can occur without alerting the user.
You are exposed to vulnerabilities.
The JSON text string could be manipulated to act as a harmful function on the server side.
eval(JSON)[0].adjacencies[0].nodeTo
may seem harmless on the surface, but it actually executes a function, posing significant risks.
To avoid these dangers, it is recommended to rely on JSON parsing tools instead of utilizing eval()
.