JSON Syntax

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 ww w .j a  v a 2 s.  com
    "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   w w w. j a  v a  2  s.  c om
 { 
    "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
 } 
]




















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions