JSON (JavaScript Object Notation) data format is widely used for data interchange. A JSON object is a key-value data format that is enclosed in curly braces. It is a human and machine readable format. JSON uses the .json file extension.
JSON file cannot have comment. The JSON should all be data, and if you include a comment, then it will be data too.
Syntax
Key-value pairs have a colon between them as in "key" : "value"
. Each key-value pair is separated by a comma. Keys are on the left side of the colon, and can be any valid string. Within each object, keys need to be unique. Below shows an example of JSON object.
{ "name" : "mymusing", "location" : "Earth" }
Tokens used in JSON document are
- “: ” separate name from value
- “,” separate name-value pairs
- “{” and “}” define an object
- “[” and “]” define an array
Below shows example of nested object with array. Object color
is nested within colors
object. colors
object has list of color
object.
{ "colors" : [ { "color" : "Red" }, { "color" : "Blue" }, { "color" : "Green" } ] }
Data Types
JSON values are found to the right of the colon. At the granular level, JSON supports below data types
- String
- Number
- Boolean
- Null/empty
- Object
- Array
String are sequence of characters, inserted between ” and “.
{ "color" : "Red" }
Number are represented in base 10 with no leading zero. It can be a fraction (e.g. .5). It can also have an exponent of 10, prefixed by e.
{ "number_positive" : 10, "number_negative" : -10, "number_fraction" : 1.05, "number_exponent" : 15.0E+2 }
Boolean value can be either true or false. If no value to assign. it can be treated as null.
{ "boolean_type" : true "null_type" : , }
Object are unordered set of name/value pairs inserted between {} (curly braces). Multiple name/value pairs are separated by a , (comma). Array is ordered collection of values. It begins with [ (left bracket) and ends with ] (right bracket). It’s values are separated by , (comma).
{ "object_type": { "color" : "Red" }, "ids" : [1,2,3] }
Accessing Object Values
JSON objects are very much like javascript objects. Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null). Object values can be accessed in two ways:
- Dot (.) notation
- Bracket ([]) notation
To loop through object values use for loop, just like looping through an array.
var num = { "number_positive" : 10, "number_negative" : -10, "number_fraction" : 1.05, "number_exponent" : 15.0E+2, "number_array" : [1, 2, 3 ,4, 5] } // Output : 10 console.log( num.number_positive ); // Output : 10 console.log( num["number_positive"]); // Output : 1 console.log( num["number_array"][0]); /* Output: number_positive - 10 number_negative - -10 number_fraction - 1.05 number_exponent - 1500 number_array - 1,2,3,4,5 */ for (x in num) { console.log(x + " - " + (num[x])); }