Skip to content

JSON Object Literals

Learn how JSON object literals work, including key/value pairs, valid data types (strings, numbers, booleans, objects, arrays, null), and how to convert JSON strings to JavaScript objects.

JSON Object

JSON object literals holds key/value pair.

Each key is represented as a string in JSON and value can be of any type.

The keys and values are separated by colon.

Each key/value pair is separated by comma.

Example:

{
	"employee": {
		"name": "Tom",
		"salary": 45000,
		"married": false
	}
}

Note that in the above example, employee is an object in which name, salary and married are the key. In this example, there are string, number and boolean value for the keys.

JSON Object Literal with Strings

The string value must be enclosed within double quote.

{
	"name": "Tom",
	"surname": "Smith"
}

JSON Object Literal with Numbers

JSON supports numbers in double precision floating-point format. The number can be digits (0-9), fractions (.33, .532 etc) and exponents (e, e+, e-, E, E+, E-).

{  
	"integer": 12,  
	"fraction": .12345,  
	"exponent": 5.6789e+0  
}  

JSON Object Literal with Booleans

JSON also supports boolean values true or false`.

{  
	"first": true,  
	"second": false  
}  

Nested JSON Object Literal

JSON objects can be nested.

{
	"name": "Tom",
	"surname": "Smith",
	"email": "tomsmith@example.com"
}

Convert JSON Object Literal to JavaScript Object

You can create a JavaScript object from a JSON object literal in this way:

let myObject= {"name":"Tom", "salary":45000, "married":false};

But more often you create a JavaScript object by parsing a JSON string with JSON.parse()

let myJSON = '{"name":"Tom", "salary":45000, "married":false}';
let myObj = JSON.parse(myJSON);

Accessing Object Values

You can access object values by using dot (.) notation:

const myJSON = '{"name":"Tom", "surname":"Smith", "salary":45000}';  
const myObj = JSON.parse(myJSON);  
x = myObj.name;

You can also access object values by using bracket ([]) notation:

const myJSON = '{"name":"Tom", "surname":"Smith", "salary":45000}';
const myObj = JSON.parse(myJSON);
x = myObj["name"];

Looping an Object

You can loop through object properties with a for-in loop:

const myJSON = '{"name":"Tom", "surname":"Smith", "salary":45000}';  
const myObj = JSON.parse(myJSON);  
  
let text = "";  
for (const x in myObj) {  
	text += x + ", ";  
}

In a for-in loop, use the bracket notation to access the property values:

const myJSON = '{"name":"Tom", "surname":"Smith", "salary":45000}';  
const myObj = JSON.parse(myJSON);  
  
let text = "";  
for (const x in myObj) {  
	text += myObj[x] + ", ";  
}
Navigation