May 06, 2021 JavaScript
5. JSON is formatted as a JavaScript object
7. JSON data - one name corresponds to one value
JSON is the format used to store and transfer data.
JSON is typically used on the service side to pass data to Web pages.
JSON uses JavaScript syntax, but the JSON format is just a text.
Text can be read by any programming language and passed as a data format. |
The following JSON syntax defines an array of employees objects: 3 employee records (objects):
The JSON format is syntaxally the same as creating JavaScript object code.
Because they are similar, JavaScript programs can easily convert JSON data to JavaScript objects.
The JSON data format is a key/value pair, just like the JavaScript object property.
The key/value pair includes the field name (in double quotes), followed by a colon, followed by a value:
"firstName":"John"
The JSON object is kept in braces.
Just like in JavaScript, an object can hold multiple key/value pairs:
{"firstName":"John", "lastName":"Doe"}
The JSON array is saved in parentheses.
Just like in JavaScript, arrays can contain objects:
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
In the above example, the object "employees" is an array. Contains three objects.
Each object is an employee's record (first and last name).
Typically, we read JSON data from the server and display it on a Web page.
Simply put, set the JSON string directly on our web page (you can also read our JSON tutorial). ):
First, create a JavaScript string with data in JSON format:
Then, use the JavaScript built-in function JSON.parse() to convert the string to a JavaScript object:
Finally, use the new JavaScript object on your page:
For more information on JSON, you can read our JSON tutorial.