Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to JavaScript eval() for parsing JSON

Quick Question. Eval in JavaScript is unsafe is it not? I have a JSON object as a string and I need to turn it into an actual object so I can obtain the data:

function PopulateSeriesFields(result) 
{
    data = eval('(' + result + ')');
    var myFakeExample = data.exampleType
}

If it helps I am using the $.ajax method from jQuery.

Thanks

like image 997
Damien Avatar asked Jun 03 '09 14:06

Damien


People also ask

Why JSON eval is not recommended for use?

Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!

Does JSON parse use eval?

eval() is used inside another function, how is a global function it is possible to access anytime. For example, JSON. parse is based on Douglas Crockford's solution, which uses eval() on line 497.

What does eval () do in JSON?

The eval() function in JavaScript is used to take an expression and return the string. As a result, it can be used to convert the string into JSON.

Is JSON Parsable JavaScript?

Parsing FunctionsFunctions are not allowed in JSON. If you need to include a function, write it as a string.


1 Answers

Well, safe or not, when you are using jQuery, you're better to use the $.getJSON() method, not $.ajax():

$.getJSON(url, function(data){
    alert(data.exampleType);
});

eval() is usually considered safe for JSON parsing when you are only communicating with your own server and especially when you use a good JSON library on server side that guarantees that generated JSON will not contain anything nasty.

Even Douglas Crockford, the author of JSON, said that you shouldn't use eval() anywhere in your code, except for parsing JSON. See the corresponding section in his book JavaScript: The Good Parts

like image 68
Rene Saarsoo Avatar answered Sep 19 '22 14:09

Rene Saarsoo