Change is in the Air
JSON's raison d'Ãªtre is to encapsulate an object in a meaningful and standardized way that can be easily understood by humans, as well as being rapidly parsed by machines. This is accomplished by structuring an object as literal representation using common programming syntax characters. Programmers have little difficulty in wrapping their heads around literals because they've been around for a long time. For instance, we almost instinctively know that the following code refers to an integer: "var intType = 3;" whereas this is a String: "var stringType = '3';" (technically a String within a String here!). Most languages can also represent more complex data types like arrays using literals such as: "var arrayLiteral = [1, '2', 3.34, 'dog'];" Notice that the array may contain several data types as well, depending on the language.
Let's get into some specifics regarding the JSON standard.
|Syntax||String Example||or||Numeric Example|
|"key": value||"name": "Fred"||"price": 55.99|
JSON supports several data types including:
- number (integer, real, or floating point)
- String (double-quoted Unicode with backslash escapement)
- boolean (true and false)
- Array (an ordered sequence of values, comma-separated and enclosed in square brackets)
- Object (collection of key/value pairs, comma-separated and enclosed in curly brackets)
Here is a sample JSON object demonstrating various data types:
Note how few characters are used. Now that's compact!
Taking JSON for a Test Drive
A common use for JSON is to pass objects between the Web page and a server-side application. In the following JSP example, a simple JSON object is constructed using the JSON Object utility class from the JSON.org home page.
The above code would send the following String to the browser. For illustration purposes, the sequence of the key-value pairs follows the same order in which they were added to the JSONObject. In practice, this wouldn't necessarily be the case, but is of no consequence; like hash tables, element ordering is a non-issue:
It can even be simpler than that! The JSONObject utility class has a constructor that accepts a Plain Old Java Object (POJO) class and a String Array. It uses class reflection to convert the public members in the Array to JSON properties. Here's how you would use the constructor:
Of course JSON works just as well going the other way. Again, there are plenty of utility scripts to choose from. As an example, here's one called JSON.js by Andrea Giammarchi. To use it, you simply call the encode function on your object like so:
Alternatively, you can create your own function by adding the JSON.encode() function to the Object prototype:
The encode's sister decode() function can then be used to parse the server response: