JSON As A Data Format
Before I discovered JSON to store data, I did all kinds of crazy things to put content in a JavaScript-ready format: arrays, strings with control characters to split, and other abominations. The creation of JSON by Douglas Crockford changed all that. Using JSON, you can store complex data in a format that is native to JavaScript and doesn't need any extra conversion to be used immediately.
JSON is short for "JavaScript Object Notation" and uses both of the shortcuts we covered earlier.
So, if I wanted to describe a band, for example, I could do the following:
02 | "name" : "The Red Hot Chili Peppers" , |
05 | "name" : "Anthony Kiedis" , |
09 | "name" : "Michael 'Flea' Balzary" , |
10 | "role" : "bass guitar, trumpet, backing vocals" |
14 | "role" : "drums,percussion" |
17 | "name" : "John Frusciante" , |
You can use JSON directly in JavaScript and, when wrapped in a function call, even as a return format of APIs. This is called JSON-P and is supported by a lot of APIs out there. You can use a data endpoint, returning JSON-P directly in a script node:
09 | document.getElementById( 'delicious' ).innerHTML = out; |
This calls the Delicious Web service to get my latest JavaScript bookmarks in JSON format and then displays them as an unordered list.
In essence, JSON is probably the most lightweight way of describing complex data—and it runs in a browser. You can even use it in PHP using the json_decode()
function.
Ingen kommentarer:
Send en kommentar