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"}');
Related
If there is a cookie on our website called cabbages and $.cookie("cabbages") returns this:
"purchaseType":"NONE","futurePurchaseType":"NONE","id":73041988,"unlimitedStatus":null,"hasFuturePrivilege":false,"corpUser":false,"suspendedStatus":null,
What is the prescribed or conventional way to get back the value of id? I want the ID of the visitor so in this example I'd like to write some Javascript that returns 73041988.
Contents of your cabbages cookie looks very close to json object syntax to me. So JSON.parse() would be naturally the way I would take. You just need to add curly braces to that string to make it valid json object syntax.
Actually this has got nothing to do with cookies. If any variable contains data having syntax similar to this, you can always go for JSON.parse() to extract it in to a javascript variable.
Json objects look like:
{name1:value1,name2:value2,name3:value3}
Similarly a json array looks like:
[value1,value2,value3]
and you could use JSON.parse for any data having json sytax.
You can see some more good examples of JSON syntax in links below.
http://json.org/example
http://www.tutorialspoint.com/json/json_syntax.htm
Please note that this JSON API which provides native support for json serialization in javascript may not be available in some older browsers and the function call will fail.
As you mentioned $.cookie() in your question, I guess that your project is already using JQuery. So you better use jQuery.parseJSON(), which makes use of JSON.parse where the browser provides a native implementation, and also provides a fall back parser when browser support is not available.
This Stack Overflow thread has more details about Native JSON support in browsers.
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.
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.
Quick questions that probably a piece of cake for someone in the know to asnwer.
I have a simple asp.net website that uses JSON for a bunch of stuff (and JSON.stringify)
All good in firefox etc, yet, in IE6 I run into an error with JSON being undefined.
Is there a way I can include a JSON implementation without breaking what I have already (using the native JSON objects in the other browsers).
If so, how?
Thanks!
The json2 library at https://github.com/douglascrockford/JSON-js is exactly what you're looking for. You can include it unconditionally, and it adds JSON.parse and JSON.stringify to your global namespace (only if there isn't one defined yet). It won't mess with any built-in JSON. From its source:
if (!this.JSON) {
this.JSON = {};
}
...
if (typeof JSON.stringify !== 'function') {
...
if (typeof JSON.parse !== 'function') {
That's comprehensive! Even if for some reason you already have JSON.stringify but not JSON.parse (or vice versa) it'll still do the right thing, leaving the original ones in place.
Your version of firefox might be having built-in support for the JSON library. But ideally you should include the JSON js library from json.org (make a copy of it in your hosted domain).
I also met this issue, you can load json2.js before using JSON. refer to this link.
Use the JSON-js made avaliable on Github by Douglas Crockford it makes the JSOn object avaliable in browsers which dont support the JSOn object natively just include a single js file in ur page which uses JSOn object. https://github.com/douglascrockford/JSON-js
Also Check out this link http://json.org/js.html
Simply check for JSON.stringify and if it doesn't exist, use some other method to parse data into a JSON string.
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.