JSON Explained
What is JSON?
JSON stands for "JavaScript Object Notation" and is pronounced "Jason" (like in the Friday the 13th movies). It's meant to be a human-readable and compact solution to represent a complex data structure and facilitate data-interchange between systems.
Why use JSON?
There are tons of reasons why you would want to use JSON:
- It's human readable... if it's properly formatted :-P
- It's compact because it doesn't use a full markup structure, unlike XML
- It's easy to parse, especially in JavaScript
- A gazillion JSON libraries are available for most programming languages
- The data structure is easy to understand
The JSON format
There are just a few rules that you need to remember:
- Objects are encapsulated within opening and closing brackets { }
- An empty object can be represented by { }
- Arrays are encapsulated within opening and closing square brackets [ ]
- An empty array can be represented by [ ]
- A member is represented by a key-value pair
- The key of a member should be contained in double quotes. (JavaScript does not require this. JavaScript and some parsers will tolerate single-quotes)
- Each member should have a unique key within an object structure
- The value of a member must be contained in double quotes if it's a string (JavaScript and some parsers will tolerates single-quotes)
- Boolean values are represented using the true or false literals in lower case
- Number values are represented using double-precision floating-point format. Scientific notation is supported
- Numbers should not have leading zeroes
- "Offensive" characters in a string need to be escaped using the backslash character
- Null values are represented by the null literal in lower case
- Other object types, such as dates, are not properly supported and should be converted to strings. It becomes the responsibility of the parser/client to manage this
- Each member of an object or each array value must be followed by a comma if it's not the last one
- The common extension for json files is '.json'
- The mime type for json files is 'application/json'
Example:
{
"anObject": {
"numericProperty": -122,
"stringProperty": "An offensive \" is problematic",
"nullProperty": null,
"booleanProperty": true,
"dateProperty": "2011-09-23"
},
"arrayOfObjects": [
{
"item": 1
},
{
"item": 2
},
{
"item": 3
}
],
"arrayOfIntegers": [
1,
2,
3,
4,
5
]
}
JSON in JavaScript
Because JSON derives from JavaScript, you can parse a JSON string simply by invoking the eval() function. The JSON string needs to be wrapped by parenthesis, else it will not work! This is the #1 problem when programmers first start to manipulate JSON strings. That being said, DON'T do this!
Example using the 'dangerous' eval():
<script type="text/language">
// A valid json string
var someJsonString = '{"someProperty":"someValue"}';
// jsonObject will contain a valid JavaScript object
var jsonObject = eval('(' + someJsonString + ')');
// Will display the string 'someValue'
alert(jsonObject.someProperty);
</script>
As pointed out by M. Clement at Inimino, a better and more secure way of parsing a JSON string is to make use of JSON.parse(). The eval() function leaves the door open to all JS expressions potentially creating side effects or security issues, whereas JSON.parse() limits itself to just parsing JSON. JSON.parse() is available natively in most recent browsers. If you need to support older browser, make use of an external JavaScript library such as Douglas Crockford's json2.js.
Example using JSON.parse():
<script type="text/language">
// A valid json string
var someJsonString = '{"someProperty":"someValue"}';
// jsonObject will contain a valid JavaScript object
var jsonObject = JSON.parse(someJsonString);
// Will display the string 'someValue'
alert(jsonObject.someProperty);
</script>
If you want to create a JSON string representation of your JavaScript object, make use of the JSON.stringify() function.
Example using JSON.stringify():
<script type="text/language">
// A valid json string
var someObject = {};
someObject.someProperty = "someValue";
// jsonString now contains a JSON string representation of someObject
var jsonString = JSON.stringify(someObject);
// Will display the string '{"someProperty":"someValue"}'
alert(jsonString);
</script>
You can also create JavaScript objects using the JSON syntax directly in your code.
Example of creating a JavaScript object using 'JSON' syntax:
<script type="text/language">
// jsonObject is a valid JavaScript object that can be used on the fly
var jsonObject = { someProperty : "someValue" };
// Will display the string 'someValue'
alert(jsonObject.someProperty);
</script>
Programming languages and JSON
The website JSON.org maintains an extensive list of JSON libraries and they are categorized in programming languages. Unfortunately, there are so many libraries out there that it's very hard to chose one! Note that VERY few JSON libraries have strict adherence to the JSON specification and this can lead to parsing problems between systems.
These are my recommended JSON libraries:
- C++: JsonCpp
- C# (.Net): Json.NET
- JAVA: JSON.smart,JSON-lib
Other useful JSON resources
- JSON.org - Excellent overall explanation and list of many JSON libraries
- Wikipedia - Brief explanation of JSON
- TheServerSide.net - A list of JSON resource guide on TheServerSide.com