JavaScript JSON

JSON is a format for storing and transmitting data.

JSON is often used when data is sent from the server to the web page.

What is JSON?

  • JSON refers to JavaScript Object Notation
  • JSON is a lightweight data interchange format
  • JSON is independent of language *
  • JSON is "self-describing" and easy to understand

* The syntax of JSON is derived from the syntax of JavaScript object notation, but the JSON format is plain text. Code to read and generate JSON data can be written in any programming language.

JSON instance

JSON syntax defines an employee object: an array (object) containing three employee records:

JSON instance

{
"employees":[
    {"firstName":"Bill", "lastName":"Gates"}, 
    {"firstName":"Steve", "lastName":"Jobs"},
    {"firstName":"Alan", "lastName":"Turing"}
]
}

JSON format is evaluated as a JavaScript object

JSON format is grammatically the same as the code for creating JavaScript objects.

Due to this similarity, JavaScript programs can easily convert JSON data to local JavaScript objects.

JSON syntax rules

  • Data is a name/value pair
  • Data is separated by commas
  • Braces save objects
  • Brackets save arrays

JSON data - names and values

The writing style of JSON data is name/value pairs, similar to JavaScript object properties.

Name/value pairs are composed of field names in double quotes, followed by a colon, and then the value:

"firstName":"Bill"

JSON names require double quotes. JavaScript names do not.

JSON Object

JSON objects are written within curly braces.

Similar to JavaScript, objects can contain multiple name/value pairs:

{"firstName":"Bill", "lastName":"Gates"}

JSON Array

JSON arrays are written within square brackets.

Similar to JavaScript, arrays can contain objects:

"employees":[
    {"firstName":"Bill", "lastName":"Gates"}, 
    {"firstName":"Steve", "lastName":"Jobs"}, 
    {"firstName":"Alan", "lastName":"Turing"}
]

In the above example, the object "employees" is an array. It contains three objects.

Each object represents a record of a person (with a first name and a last name).

Convert JSON text to a JavaScript object

The usual usage of JSON is to read data from a web server and then display the data on a webpage.

For simplicity, a string can be used as input for demonstration.

Firstly, create a JavaScript string with JSON syntax:

var text = '{ "employees" : [
'{ "firstName":"Bill" , "lastName":"Gates" },' +
'{ "firstName":"Steve" , "lastName":"Jobs" },' +
'{ "firstName":"Alan" , "lastName":"Turing" } ]}';

Then, use JavaScript's built-in function JSON.parse() to convert this string to a JavaScript object:

var obj = JSON.parse(text);

Finally, please use this new JavaScript object on your page:

Example

<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script> 

Try it yourself

You can try our JSON tutorial Read more about JSON in Chinese.