W3Schools.com

JSON Syntax


JSON syntax is a subset of JavaScript syntax


JSON Syntax Rules

JSON syntax is a subset of the JavaScript object notation syntax.

  • Data is in name/value pairs
  • Data is separated by comma
  • Curly brackets holds objects
  • Square brackets holds arrays

JSON Name/Value Pairs

JSON data is written as name/value pairs.

A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

"firstName" : "John"

This is simple to understand, and equals to the JavaScript statement:

firstName = "John"


JSON Values

JSON values can be:

  • A number (integer or floating point)
  • A string (in double quotes)
  • A Boolean (true or false)
  • An array (in square brackets)
  • An object (in curly brackets)
  • null

JSON Objects

JSON objects are written inside curly brackets,

Objects can contain multiple name/values pairs:

{ "firstName":"John" , "lastName":"Doe" }

This is also simple to understand, and equals to the JavaScript statements:

firstName = "John"
lastName = "Doe"


JSON Arrays

JSON arrays are written inside square brackets.

An array can contain multiple objects:

{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}

In the example above, the object "employees" is an array containing three objects. Each object is a record of a person (with a first name and a last name).


JSON Uses JavaScript Syntax

Because JSON uses JavaScript syntax, no extra software is needed to work with JSON within JavaScript.

With JavaScript you can create an array of objects and assign data to it like this:

Example

var employees = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
];

The first entry in the JavaScript object array can be accessed like this:

employees[0].lastName;

The returned content will be:

Doe

The data can be modified like this:

employees[0].lastName = "Jonatan";

Try it yourself »
 

In the next chapter you will learn how to convert a JSON text to a JavaScript object.


JSON Files

  • The file type for JSON files is ".json"
  • The MIME type for JSON text is "application/json"


WEB HOSTING
Best Web Hosting
PHP MySQL Hosting
Best Hosting Coupons
UK Reseller Hosting
Cloud Hosting
Top Web Hosting
$3.98 Unlimited Hosting
Premium Website Design
WEB BUILDING
Download XML Editor
FREE Website BUILDER
Best Website Templates Top CSS Templates
CREATE HTML Websites
EASY WEBSITE BUILDER
W3SCHOOLS EXAMS
Get Certified in:
HTML, CSS, JavaScript, XML, PHP, and ASP
W3SCHOOLS BOOKS
New Books:
HTML, CSS
JavaScript, and Ajax
STATISTICS
Browser Statistics
Browser OS
Browser Display
SHARE THIS PAGE