Saturday, April 12, 2014

JSON - JavaScript Object Notation

JSON is a string-based format that represents data in a platform-independent manner. JSON is less verbose than an equivalent XML representation.

Value Types

  • strings (enclosed in double quotes) - Control characters: \"  \\  \/  \b  \f  \n  \r  \r   \t   \u four-hex-digits
  • numbers (octal and hex formats not supported; integers, real numbers, e notation supported)
  • objects
  • arrays
  • true
  • false
  • null

Arrays

["red", "green", "blue"]

Array values are enclosed in square brackets, separated by commas. An array is ordered. An array can contain any type of value. The following array contains two objects.

[{"name": "john, "age": 5}, {"name":"sam", "age": 6.5} ]

Internally, arrays are objects as well (keys are index values, 0,1, ...).

 Objects

An object is an unordered set of name/value pairs. Enclosed in curly brackets. Key/values are separated by a colon. Pairs are separated by commas.
{
    "id": 1000,
    "name": "Laptop",
    "price": 1200.50,
    "available": true,
    "discount": false,
    "specs" : { "processor": "i7", "graphicscard" : null},
    "tags": ["home", "green"]
}

An object may contain values of any supported type. Look for a nested object and an array in the above example.

// iterate through all properties of an object
function objProperties(obj) {
        var ret = [];
        if (obj) {
            for (var property in obj) {
                if (obj.hasOwnProperty(property)) {
                }
            }
        }
        return ret;
    }

JSON processing in js

JSON.stringify turns a Javascript object into JSON text and stores that JSON text in a string.

JSON.parse turns a string of JSON text into a Javascript object.

Reference: http://json.org/