How do I use JSON in older browsers? - javascript

In javascript, I want to use JSON.stringify. But some (older) browsers do not recognize JSON as a defined object. Is there a javascript file that I can include that defines JSON, and all it's awesome functionality, for browsers that do not natively support JSON?
I should note that I'm referring to a specifically defined JSON object, rather than the more general concept of javascript object notation.

Douglas Crockford (the inventor of JSON) provides json2.js, an efficient JSON "parser" that doesn't actually parse JSON; it uses regular expressions to sanitise JSON before passing it to eval, and falls back on native JSON support if the browser has it.
He also provides a more conventional recursive-descent parser and a state-machine-based parser in the same repo.

Related

Can Kotlin or Swift parse JSON just like Javascript?

If I'm using javascript (or TypeScript), I can do following (just idea);
object = JSON.parse(jsonString)
And I can just use it like this,
alert(object.property);
Super Simple.
If I'm using Java, I need to create classes and parse it to use it. I understand.
How about Kotlin and Swift. They have optional types, so why single line, Javascript-like simple parsing doesn't exist for them, or does it? (Without even data class or going through JSON's properties)
If you look up what JSON stands for it's no wonder why JavaScript has "native support" for it: JavaScript Object Notation
In Kotlin you'll need to use libraries for parsing JSON, I'd recommend Jackson for that, a library widely used with Java already.

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.

JSON object in IE6 - How?

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.

JSON serialization in Spidermonkey

I'm using python-spidermonkey to run JavaScript code.
In order to pass objects (instead of just strings) to Python, I'm thinking of returning a JSON string.
This seems like a common issue, so I wonder whether there are any facilities for this built into either Spidermonkey or python-spidermonkey.
(I do know about uneval but that is not meant to be used for JSON serialization - and I'd rather avoid injecting a block of JavaScript to do this.)
I would use JSON.stringify. It's part of the ECMAScript 5 standard, and it's implemented in the current version of spidermonkey. I don't know if it's in the version used by python-spidermonkey, but if it isn't, you can get a JavaScript implementation from http://www.json.org/js.html.

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