JSON Object


1. Key-Value Pairs

JSON uses key-value pairs to express an object's property. In the above example, we tried to represent a Person. This person has some properties like

  • First Name
  • Age
  • Address

Each of these properties have a value associated with it. For instance, the value of First Name is Rohatash. Age also has a value of 35. The rules for writing a Key-Value in JSON are as follows.

  • Key-value pairs are separated by a : (colon)
  • Key is always present in Double Quotes " "
  • Values must be valid JSON data types: string, number, another JSON object, array, boolean or null.

From the above example, a Key-Value pair is FirstName.

"FirstName" : "Rohatash"

As you can see in the figure below:

{"FirstName" : "Rohatash","Age" : 35,"Address" : "Mathura"}

Json Object

2. JSON Objects Example

In JSON an object is represented by a collection of Key-Value pairs. This collection of Key-Value pairs are grouped using { } (opening and closing curly braces}. The rules for writing a Key-Value in JSON are as follows.

  • Key-Value pairs should be separated by a, (Comma)
  • Each Object should Start with an Opening {(Opening Curly Brace).

Example

In this example, Object start with { (Opening Curly Brace) and end with } (Ending Curly Brace).

{
   "FirstName" : "Rohatash",
   "Age" : 35,
   "Address" : "Mathura"
} 

As you can see in the figure below:

Json Object

3. Nested JSON Object

Objects can be nested inside other objects. Each nested object must have a unique access name.

Example

In this example, we have created a object qualification inside object.

{  
     "firstName": "Rohatash",       
     "age": 36,  
     "Qualification" : {  
         "Masterdegree": "MCA",  
         "Graduation": "BCA",         
     }  
}  

The same field name can occur in nested objects in the same document. However, the full access name must still be unique.

{  
     "firstName": "Rohatash",       
     "age": 36,  
     "author": 
     {
      "firstname": "Rohatash Kumar"
     },
     "Qualification" : {  
         "Masterdegree": "MCA",  
         "Graduation": "BCA",         
     }      
 } 

In the example, the field name firstName occurs in the parent object and the author object. The prefixes in author object author.firstName provide unique access.


Prev Next