JSON Object Literals
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.
Keys must be strings, and values must be a valid JSON data type:
- string
- number
- object
- array
- boolean
- null
JSON object liter is commonly called "JSON object", but it is a mistake!
JSON can't be an object. JSON is a string format.
The data is only JSON when it is in a string format. It becomes a JavaScript object only when the JSON string is converted to a JavaScript variable.
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": "[email protected]"
}
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] + ", ";
}