JSON arrays are enclosed in square brackets.
Just like in JavaScript, an array can contain objects.
“employees”:[ {“firstName”:“John”, “lastName”:“Doe”}, {“firstName”:“Anna”, “lastName”:“Smith”}, {“firstName”:“Peter”, “lastName”:“Jones”} ] |
In the example above, the employees object is an array containing three objects.
Each object represents a person’s record, with a first name and a last name.
A common use of JSON is to retrieve data from a web server and display it on a web page.
For simplicity, this can be demonstrated using a string that contains JSON syntax.
First, create a JavaScript string with JSON format.
let text = ‘{ “employees” : [‘ + ‘{ “firstName”:”John” , “lastName”:”Doe” },’ + ‘{ “firstName”:”Anna” , “lastName”:”Smith” },’ + ‘{ “firstName”:”Peter” , “lastName”:”Jones” } ]}’; |
Next, use the JavaScript built-in function JSON.parse()
to convert the string into a JavaScript object.
const obj = JSON.parse(text); |
Finally, use the newly created JavaScript object in your page.
<p id=”demo”></p> <script> document.getElementById(“demo”).innerHTML = obj.employees[1].firstName + ” “ + obj.employees[1].lastName; </script> |