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.
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.
New to JSON, just trying to get my feet wet.
I know how to do this with XML via javascript, but am trying to learn how to handle JSON objects so I can switch over.
Basically I want to search through all "permalink" tags in the following JSON object and, when I find the right one, save its corresponding "title" and "id" tags to javascript variables:
http://api.soundcloud.com/users/goldenstatewarriors/tracks.json?client_id=02db8e29aa2fb5bf590f478b73137c67
Can this be done with only javascript (no PHP)? The main issue I'm facing is simply grabbing the text from the page and converting it to a json object.
You need to use a JSON parser in order to transform the JSON string into an object you can handle natively in JavaScript. Recent browsers have this functionality built in as JSON.parse(), but obviously this will not work in older browsers (we're talking very old browsers here).
A solution to that problem is to use the JSON parsing library available here. If native browser support is detected, it simply uses that, otherwise it has a JavaScript implementation to achieve the same result. The file you'll need is json2.js - simply include that as you would any other library and away you go!
An example of the code would be:
var dataObject = JSON.parse(jsonData);
As a side note, XMLHttpRequest is somewhat of a misnomer these days. It is simply a mechanism for making HTTP requests and retrieving the data returned, it doesn't have to be XML. It can be plain text, (non X)HTML, JSON, anything. In fact, I don't think I've seen anything in the wild return actual XML data for an XMLHttpRequest in a very long time.
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.
I'm building an AJAJ (AJAX with JSON) webapp with jQuery and I'd like my users to be able to bookmark a page that saves all of their setting selections for a certain part of the app. I've got quite a bit of data that needs to be saved, so I thought JSON might be the best way to save this, putting it into the location.hash.
That being said, what's the best way to get the string of data from the location.hash and convert it back to a JSON object so that it's usable inside the Javascript?
Here's what I'm thinking as far as the JSON object
http://example.com/index.html#json={'s': '2010-02-19', 'array':[1,2,3,4]}
Roland suggested that I drop the json=, successfuly cutting 5 characters out, too. So the complete location would be:
http://example.com/index.html#{'s': '2010-02-19', 'array':[1,2,3,4]}
Example assuming you have JSON support (either native or by including a JSON parse script)
var obj, text = document.location.hash;
if (text){
obj = JSON.parse(text);
}
If the browser does not have native JSON support, you can grab a script from http://www.json.org/js.html or use some framework supported variant (like YUI's http://developer.yahoo.com/yui/json/)
You say 'quite a bit'. Can you be more specific? Bear in mind that you are limited to 2083 characters on your URL.
Personally, I would be reticent to store this sort of stuff in the command line anyway. You'll have pain dealing with URL encoding/decoding, and people can get an Idea of your data structures, and possibly hack the JSON string in the URL.
Have a look at the history plugin, it might be relevant to your needs
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"}');