JSON.parse vs. eval() - javascript

My Spider Sense warns me that using eval() to parse incoming JSON is a bad idea. I'm just wondering if JSON.parse() - which I assume is a part of JavaScript and not a browser-specific function - is more secure.

You are more vulnerable to attacks if using eval: JSON is a subset of Javascript and json.parse just parses JSON whereas eval would leave the door open to all JS expressions.

All JSON.parse implementations most likely use eval()
JSON.parse is based on Douglas Crockford's solution, which uses eval() right there on line 497.
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
The advantage of JSON.parse is that it verifies the argument is correct JSON syntax.

Not all browsers have native JSON support so there will be times where you need to use eval() to the JSON string. Use JSON parser from http://json.org as that handles everything a lot easier for you.
Eval() is an evil but against some browsers its a necessary evil but where you can avoid it, do so!!!!!

There is a difference between what JSON.parse() and eval() will accept. Try eval on this:
var x = "{\"shoppingCartName\":\"shopping_cart:2000\"}"
eval(x) //won't work
JSON.parse(x) //does work
See this example.

If you parse the JSON with eval, you're allowing the string being parsed to contain absolutely anything, so instead of just being a set of data, you could find yourself executing function calls, or whatever.
Also, JSON's parse accepts an aditional parameter, reviver, that lets you specify how to deal with certain values, such as datetimes (more info and example in the inline documentation here)

JSON is just a subset of JavaScript. But eval evaluates the full JavaScript language and not just the subset that’s JSON.

Related

How to parse a string to an array of array using Javascript

I am trying to use JSON.parse to parse a string to the array of array, such as
var a = "[['1909-23', 'egg']]"
JSON.parse(a)
It gives me the SytaxError. Wonder if there is any easy way to solve it. Thanks.
The string
"[['1909-23', 'egg']]"
Is not a valid JSON string. As such you can't call JSON.parse() on it.
The JSON format requires double quotes around strings.
A solution would be then to use double quotes:
var a = '[["1909-23", "egg"]]';
console.log(JSON.parse(a));
Before you use this, please read Why is using the JavaScript eval function a bad idea?. This will potentially open up your JavaScript to code injection attacks. A much better solution is to actually turn your string into correct JSON and parse is using JSON.parse
That all said, you can “parse” (actually you've executing the string as javascript, hence the injection problem) this string using eval.
var a = "[['1909-23', 'egg']]"
var b = eval(a);
console.log(b);
Note the warning on MDN
Do not ever use eval!
eval() is a dangerous function, which executes the code it's passed
with the privileges of the caller. If you run eval() with a string
that could be affected by a malicious party, you may end up running
malicious code on the user's machine with the permissions of your
webpage / extension. More importantly, a third-party code can see the
scope in which eval() was invoked, which can lead to possible attacks
in ways to which the similar Function is not susceptible.
eval() is also slower than the alternatives, since it has to invoke
the JS interpreter, while many other constructs are optimized by
modern JS engines.
Additionally, modern javascript interpreters convert javascript to
machine code. This means that any concept of variable naming gets
obliterated. Thus, any use of eval will force the browser to do long
expensive variable name lookups to figure out where the variable
exists in the machine code and set it's value. Additonally, new things
can be introduced to that variable through eval() such as changing the
type of that variable, forcing the browser to reevaluate all of the
generated machine code to compensate. However, there (thankfully)
exists a very good alternative to eval: simply using window.Function.
As an example of how you convert code using evil eval() to using
Function(),

How to parse JSON in Mongo script

As part of a MongoDB script, I need to parse JSON. (Not something you would typically do, but it is Javascript after all).
JSON.parse does not exist.
Here is the workaround I made:
function parseJSON(json) {
return eval("(function() { return "+json+"; })()");
}
This doesn't seem like it would be performant, and it looks a little ridiculous. Does anyone have a better way?
If you really have to convert a JSON string into a JavaScript object, then what you suggest is perfectly reasonable, although there are reasons to avoid eval due to performance concerns and security risks (see When is JavaScript's eval() not evil?). In the case that you generated the JSON data and you are sure that there's nothing dangerous inside, then you probably don't have to worry about an injection vulnerability.
As far as performance, I'm not aware of anything better other than JSON.parse. Can you alter the design of your program so that you do not have to parse JSON? For example, for importing JSON data into MongoDB, instead of using eval you should use the mongoimport utility.

Need less restrictive json parser

I need to pass different strings formatted as json to a json parser.
Problem is that jQuery.parseJSON() and JSON.parse() only support a very strict json format:
Passing in a malformed JSON string may result in an exception being thrown. For example, the following are all malformed JSON strings:
{test: 1} (test does not have double quotes around it).
{'test': 1} ('test' is using single quotes instead of double quotes).
Is there a less restrictive parser that will allow passing values like that (without quotes or with single quote)?
BTW, I'm using KO 2.2.1 so if it has something like that it would be helpful.
There is a node module called jsonic that parses non strict JSON.
npm install jsonic
You might also use eval:
var parsed = eval(json)
Be careful because eval could also run code so you must be sure that you know what you are parsing.
There is no such thing as a less strict JSON parser. You're either dealing with well-formed JSON, or you're not dealing with JSON at all. To parse your custom format, you may want to take a look at Crockford's parser source code, and modify it to fit your needs.
Or, for a quick and dirty solution you might just use eval (but be aware its use has security implications).

JSON to JavaScript object #text property

I am currently developing a JavaScript add-on which receives JSON from an API. So far, so good I retrieve the JSON and then use eval() to convert this JSON to a JavaScript object. This is where the problems start.
My JSON contains a '#text'-property. I evaluated the JavaScript object and found it also has this '#text'-property, but I can not call the property since variables with hash-tags are not accepted.
I know two possible solutions (use eval() to convert to an Array or remove the hast-tag), but I would prefer calling the property. Any ideas? Thanks.
You can reference object properties with square brackets:
var obj = {'#foo': 'bar'};
obj['#foo']; // 'bar'
Indeed, obj.#foo is invalid (i.e. will raise a syntax error), but the above method is fine.
Also, don't use eval unless you have to. Despite being a slower solution, it's less safe, especially considering there are usually so many native JSON methods, and most JSON libraries will introduce the functionality only if the native methods don't exist.
Don't use eval, especially for this. You a json parser, modern browsers already have them.
var myObj = JSON.parse(returnFromServer);
console.log(myObj.firstProperty); // etc
Here's a CDN link for json2 http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js
Do stuff before eval like replacing hash sign with something else.

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
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
You should use JSON and write JSON.parse.
"Manual" parsing is too slow, so JSON.parse implementation from the library checks stuff and then ends up using eval, so it is still unsafe. But, if you are using a newer browser (IE8 or Firefox), the library code is not actually executed. Instead, native browser support kicks in, and then you are safe.
Read more here and here.
If you can't trust the source, then you're correct...eval is unsafe. It could be used to inject code into your pages.
Check out this link for a safer alternative:
JSON in Javascript
The page explains why eval is unsafe and provides a link to a JSON parser at the bottom of the page.
Unsafe? That depends on if you can trust the data.
If you can trust that the string will be JSON (and won't include, for example, functions) then it is safe.
That said - if you are using jQuery, why are you doing this manually? Use the dataType option to specify that it is JSON and let the library take care of it for you.
If you are using jQuery, as of version 1.4.1 you can use jQuery.parseJSON()
See this answer: Safe json parsing with jquery?
Using JavaScript’s eval is unsafe. Because JSON is just a subset of JavaScript but JavaScript’s eval allows any valid JavaScript.
Use a real JSON parser like the JSON parser from json.org instead.
The alternative to evaluating the code is to parse it manually. It's not as hard as it sounds but it's quite a lot heavier at runtime. You can read about it here.
The important part to note is evaluating JSON is not inherently insecure. As long as you trust the source not to balls things up. That includes making sure that things passed into the JSON encoder are properly escaped (to stop people 2 steps up the stream executing code on your users' machines).
you can try it like this
var object = new Function("return " + jsonString)()
Another great alternative is YUI:
http://yuilibrary.com/yui/docs/json/
So your code would be something like:
Y.JSON.parse('{"id": 15, "name": "something"}');

Categories