JSON Syntax

JSON Syntax

Rules of JSON Syntax

  • JSON syntax is derived from JavaScript object notation syntax:
  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays
  • JSON names require double quotes. JavaScript names don't.

JSON Data - A Name and a Value

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:

Example:

"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 braces)
  • null

JSON Objects

JSON objects are written inside curly braces.

Just like JavaScript, JSON objects can contain multiple name/values pairs:

Example:

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

JSON Arrays

JSON arrays are written inside square brackets ie :[].

Just like JavaScript, a JSON array can contain multiple objects:

Example:

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



In the example above, the object "customers" 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 syntax is derived from JavaScript object notation, very little 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 customers = [
    {"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:

Example:

// returns John Doe
customers[0].firstName + " " + employees[0].lastName;

Try it Yourself

It can also be accessed like this:

Example:

// returns John Doe
customers[0]["firstName"] + " " + employees[0]["lastName"];

Try it Yourself

Data can be change like this:

Example:

customers[0].firstName = "Gilbert";

Try it Yourself

It can also be change like this:

Example:

customers[0]["firstName"] = "Gilbert";

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"

Share on Google Plus

About Blogger

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment

Thank You...!