JSON Syntax

JS Tutorial

JS Version

JS Objects

JS Function

JS Classes

JS Async

JS HTML DOM

JS Browser BOM

JS Web API

JS AJAX

JS JSON

JS vs JQUERY

JS Graphics

JSON Syntax

JSON Syntax Rules

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 Data – A Name and a Value

JSON data is written in the form of name/value pairs (aka key/value pairs).

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

Example

“name”:”John”

JSON – Evaluates to JavaScript Objects

The JSON format is similar to JavaScript objects.

In JSON, keys must be strings, written with double quotes:

JSON

{“name”:”John”}

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

JavaScript

{name:”John”}

JSON Values

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

  • a string.
  • a number.
  • an object.
  • an array.
  • a Boolean.
  • Null.

In JavaScript values can be all of the above, plus any other valid JavaScript expression, including:

  • a function.
  • a date.
  • Undefined

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

JavaScript Objects

Because JSON syntax is derived from JavaScript object notation, less extra software is needed to work with JSON within JavaScript.

JavaScript allows you to create an object and assign data to it, like this:

Example

person = {name:”John”, age:31, city:”New York”};

You can access a JavaScript object like this:

Example

<!DOCTYPE html>

<html>

<body>

<h2>Access a JavaScript object</h2>

<p id=”demo”></p>

<script>

const myObj = {name:”Devid”, age:30, city:”New York”};

document.getElementById(“demo”).innerHTML = myObj.name;

</script>

</body>

</html>

Output

Access a JavaScript object

It can also be accessed like this:

Example

<!DOCTYPE html>

<html>

<body>

<h2>Access a JavaScript object</h2>

<p id=”demo”></p>

<script>

const myObj = {name:”Devid”, age:30, city:”New York”};

document.getElementById(“demo”).innerHTML = myObj[“name”];

</script>

</body>

</html>

Output

Access a JavaScript object

Devid