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.
Related
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(),
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.
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.
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"}');