Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JSON Syntax

The JSON syntax is a simplified version of the JavaScript syntax.

JSON Syntax Rules

JSON syntax is based on JavaScript object notation:

  • Data is represented as name/value pairs
  • Items are separated by commas
  • Curly braces define objects
  • Square brackets define arrays

JSON Data – A Name and a Value

JSON data is composed of name/value pairs (also known as key/value pairs).

Each pair consists of a field name (in double quotes), followed by a colon, and then the corresponding value.

Example

“name”:“John”
In JSON, names (or keys) must be enclosed in double quotes.

JSON – Evaluates to JavaScript Objects

The JSON format closely resembles JavaScript objects, but in JSON, keys must be strings enclosed in 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 following data types:

  • A string
  • A number
  • An object
  • An array
  • A boolean
  • null

In JavaScript, values can be all of the above, plus other valid expressions such as:

  • A function
  • A date
  • undefined

Additionally, in JSON, string values must always be enclosed in double quotes.

JSON

{“name”:“John”}

In JavaScript, string values can be written using either double or single quotes.

JavaScript

{name:‘John’}

JavaScript Objects

Since JSON syntax is based on JavaScript object notation, minimal additional software is required to work with JSON in JavaScript.

In JavaScript, you can 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

// returns John
person.name;

It can also be accessed in this manner:

Example

// returns John
person[“name”];

Data can be updated in the following way:

Example

person.name = “Gilbert”;

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

JavaScript Arrays as JSON

Just like JavaScript objects, JavaScript arrays can also be written as JSON. You will learn more about objects and arrays later in this tutorial.

JSON Files

JSON files have the “.json” extension, and the MIME type for JSON text is “application/json”.