JSON Syntax

JSON syntax is a subset of JavaScript syntax.

JSON syntax rules

JSON syntax is derived from the syntax of JavaScript object notation:

  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces contain objects
  • Square brackets contain arrays

JSON data - name and value

JSON data is written as name/value pairs.

Name/value is composed of field name, followed by a colon and the value:

Example

"name":"Bill Gates"

JSON names need double quotes. JavaScript names do not.

JSON – evaluates to JavaScript object

JSON format is almost identical to JavaScript object format.

In JSON, keys must be strings enclosed in double quotes:

JSON

{ "name":"Bill Gates" }

In JavaScript, keys can be strings, numbers, or identifier names:

JavaScript

{ name:"Bill Gates" }

JSON value

In JSON, values must be one of the following data types:

  • String
  • Number
  • Object (JSON object)
  • Array
  • Boolean
  • null

In JavaScript, the above can be values, as well as other valid JavaScript expressions, including:

  • Function
  • Date
  • undefined

In JSON, string values must be written with double quotes:

JSON

{ "name":"Bill Gates" }

In JavaScript, you can write string values using either double quotes or single quotes:

JavaScript

{ name:'Bill Gates' }

JSON uses JavaScript syntax

Since JSON syntax is derived from JavaScript object notation, there is rarely a need for additional software to process JSON in JavaScript.

Through JavaScript, you can create objects and assign data to them, like this:

Example

var person =  { name : "Bill Gates", age : 62, city : "Seattle" };

You can access JavaScript objects like this:

Example

// Returns Bill Gates
person.name;

Try It Yourself

You can also access it like this:

Example

// Returns Bill Gates
person["name"];

Try It Yourself

You can modify the data like this:

Example

person.name = "Steve Jobs";

Try It Yourself

You can also modify it like this:

Example

person["name"] = "Steve Jobs";

Try It Yourself

Later in this tutorial, you will learn how to convert JavaScript objects to JSON.

JavaScript Arrays as JSON

Just like using JavaScript objects as JSON, JavaScript arrays can also be used as JSON.

You will learn more about JSON arrays later in this tutorial.

JSON File

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