* JSON is easy for humans to read and write.
* JSON is easy for machines to parse and generate.
* JSON is based on a subset of the JavaScript Programming Language.
* JSON is notably used by APIs all over the web and is a fast alternative to XML in Ajax requests.
* JSON is a text format that is completely language independent
JSON Encoding: Prototype provides following methods for encoding
Methods | Description |
Returns a JSON string for the given Number. | |
Returns a JSON string for the given String. | |
Returns a JSON string for the given Array. | |
Returns a JSON string for the given Hash. | |
Converts the date into a JSON string (following the ISO format used by JSON). | |
Returns a JSON string for the given Object. |
JSON Encoding:
If you are unsure of what type the data you need to encode is, your best bet is to use Object.toJSON like so:
var data = {name: 'Violet', occupation: 'character', age: 25 };
Object.toJSON(data);
This will produce following result:
'{"name": "Violet", "occupation": "character", "age": 25}'
Furthermore, if you are using custom objects, you can set your own toJSON method which will be used by Object.toJSON. For example:
var Person = Class.create();
Person.prototype = {
initialize: function(name, age) {
this.name = name;
this.age = age;
},
toJSON: function() {
return ('My name is ' + this.name +
' and I am ' + this.age + ' years old.').toJSON();
}
};
var john = new Person('John', 49);
Object.toJSON(john);
This will produce following result:
'"My name is John and I am 49 years old."'
Parsing JSON: In JavaScript, parsing JSON is typically done by evaluating the content of a JSON string. Prototype introduces String.evalJSON to deal with this. For example:
var d='{ "name":"Violet","occupation":"character" }'.evalJSON();
d.name;
This will produce following result:"Violet"
Using JSON with Ajax: Simply invoke String.evalJSON on the transport's responseText property:
new Ajax.Request('/some_url', {
method:'get',
onSuccess: function(transport){
var json = transport.responseText.evalJSON();
}
});
If your data comes from an untrusted source, be sure to sanitize it:
new Ajax.Request('/some_url', {
method:'get',
requestHeaders: {Accept: 'application/json'},
onSuccess: function(transport){
var json = transport.responseText.evalJSON(true);
}
});
No comments:
Post a Comment