JSON

In this chapter you will learn:

  1. What is JSON
  2. What is JSON Syntax
  3. How to use JSON to represent simple values
  4. How to use JSON to represent objects
  5. How to use JSON to represent arrays

What is JSON

JSON stands for JavaScript Object Notation. It uses JavaScript to represent structured data. JSON is a data format, not a programming language.

JSON Syntax

JSON syntax allows the representation of three types of values:

ValueDescription
Simple ValuesStrings, numbers, Booleans, and null can be represented in JSON using the same syntax as JavaScript. undefined is not supported.
Objectsrepresent ordered key-value pairs. Each value may be a primitive type or a complex type.
Arraysrepresent an ordered list of values that are accessible by a numeric index. The values may be simple values, objects, and other arrays.

There are no variables, functions, or object instances in JSON.

Simple Values

In its simplest form, JSON represents a small number of simple values. For example, the following is valid JSON:

5

The following is an valid JSON representing a string:

"Hello world"

JSON strings must use double quotes.

Objects

Object literals in JavaScript look like this:

var tutorial = { 
    name: "JavaScript", 
    page: 9 
};

The JSON representation of this same object is:

{ 
    "name": "JavaScript", 
    "page": 9 
}

There is no trailing semicolon. The quotes around the property name are required. The value can be any simple or complex value:

{ //from  ja va2  s .  c o  m
    "name": "JavaScript", 
    "page": 9, 
    "topic": {
         "name":    "Data Type", 
         "content": "Number" 
     } 
}

Arrays

Arrays are represented in JSON using array literal notation from JavaScript. For example, this is an array in JavaScript:

var values = [1, "JavaScript", true];

You can represent this same array in JSON using a similar syntax:

[1, "JavaScript", true]

Arrays and objects can be used together to represent more complex collections of data, such as:

[/*from j av a 2  s  .  c  o  m*/
 { 
    "title": "JavaScript", 
    "authors": ["J"],
     edition: 3,
     year: 2011

 }, 
 { 
    "title": "HTML", 
    "authors": [ "H" ],
     edition: 2,
     year: 2009
 },
 { 
    "title": "Ajax", 
    "authors": ["X", "Y", "Z" ], 
    edition: 2, 
    year: 2008
 },
 { 
    "title": "CSS", 
    "authors": ["A", "B", "C" ], 
     edition: 1, 
     year: 2007
 },
 { 
    "title": "Java", 
    "authors": ["C"],
     edition: 1,
     year: 2006
 } 
]

Next chapter...

What you will learn in the next chapter:

  1. Create JSON object from string
  2. How to use JSON.parse() to create JSON object
  3. How to control and use the parsing options in JSON parsing
Home » Javascript Tutorial » JSON
JSON
Parsing
Serialization