Tutorial: JSON Format

The beauty of JSON is it can stringify a multidimensional array, either indexed or associative array, into a linear string, so it can be passed between functions as well as languages. The basic rule is as follows:

1. If value is numeric, do not include the quote. If the value is string, include the double quote. For instance: 1, 3, "ab", "5". It is not necessary to use quote for the key in associative array if no whitespace used in key, else, use double quote. However, double quote on keys is required by JSON format specification.

2. Use ":" to separate key and value if the element is of associative relationship. For instance: Category_2:3.

3, use comma to separate elements. For instance: 1, Category_2:3, "ab".

4. Use [] to signify a single dimensional indexed array. For instance [1, 3, "ab"]. When calling an element within a single indexed dimensional array, just like usual: arr[2]. In this case, it would return 3.

5. Use {} to signify a single dimensional associative array. For instance {Category_2:3}. For multi-elements associative array, one bracket is enough: {Category_2:3, Category_3:"ab"}. When calling an element within a single associative dimensional array, use following format: arr.Category_3. In this case, it would return "ab".

Here is an example:

{lastName: "Smith",
age: 25,
address:
{streetAddress: "21 2nd Street",
postalCode: "10021"
},
phoneNumber:
[{ type: "home",
},
{ type: "fax",
number: "646 555-4567"
}
]
}

To get fax number here, call: arr.phoneNumber[1].number

Another example starts with index array:

[
{A:a}
,{B:b}
]

How to stringify JSON for multidimensional array? DON't use JavaScript built-in function stringify(). It does not work for multidimensional array. Use ''+arr to make it string.


http://en.wikipedia.org/wiki/Json

No comments:

Post a Comment

Labels