What is JSON syntax?

Share

JSON stands for Javascript Object Notation. JSON is a simple, text-based format to store and interchange data over the web.

In JSON, we create Javascript-like objects to store data. The following rules are applied when creating JSON objects:

  • Each object is enclosed within curly braces.
  • The data is stored using key-value pairs.
  • A comma separates each key-value pair.
  • Each key is written inside double-quotation marks.
  • Each array is enclosed within square brackets, and each nested object is enclosed within curly braces.
  • Each key must be unique.

Syntax

The following snippet of code shows the general syntax of a JSON object:

{
"key-1" : value-1,
"key-2" : value-2,
"key-3" : value-3
}

In the above snippet of code, we can replace the keys and values with the values that are to be stored.

Supported data types

JSON supports 6 data types, meaning that the values stored against the keys can be of 6 types. These types are:

  • string
  • number
  • boolean
  • null
  • array
  • object

Example

The following piece of code shows a JSON object that stores the data of a student. It contains all types of data.

{
"name" : "Peter",
"age" : 17,
"primary_email" : "peter@educative.io",
"secondary_email" : null,
"account_verified" : true,
"marks" : {"english" : 100, "mathematics" : 90, "physics" : 77},
"clubs_joined" : ["football", "cricket"]

}

The values stored against the name and primary_email keys are strings in the above JSON object. The value stored against the key age is a number. The value against secondary_email is null, whereas the value against account_verified is a boolean.

The value against the marks key is another JSON object. Inside this object, each stored value is a number.

The value against the clubs_joined key is an array of strings.

Copyright ©2024 Educative, Inc. All rights reserved