JSON stands for JaScript Object Notation
JSON is a lightweight format for storing and transporting data
JSON is often used when data is sent from a server to a web page
JSON is "self-describing" and easy to understand
JSON ExampleThis example defines an employees object: an array of 3 employee records (objects):
{"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]}Learn JSON Now!
JSON Syntax Rules Data is in name/value pairs Data is separated by commas Curly braces hold objects Square brackets hold arrays JaScript Object NotationThe JSON format is syntactically identical to the code for creating JaScript objects.
Because of this similarity, a JaScript program can easily convert JSON data into native JaScript objects.
The JSON syntax is derived from JaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written in any programming language.
JSON Data - A Name and a ValueJSON data is written as name/value pairs, just like JaScript object properties.
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:
"firstName":"John"JSON names require double quotes. JaScript names do not.
JSON ObjectsJSON objects are written inside curly braces.
Just like in JaScript, objects can contain multiple name/value pairs:
{"firstName":"John", "lastName":"Doe"} JSON ArraysJSON arrays are written inside square brackets.
Just like in JaScript, an array can contain objects:
"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]In the example above, the object "employees" is an array. It contains three objects.
Each object is a record of a person (with a first name and a last name).
Converting a JSON Text to a JaScript ObjectA common use of JSON is to read data from a web server, and display the data in a web page.
For simplicity, this can be demonstrated using a string as input.
First, create a JaScript string containing JSON syntax:
var text = '{ "employees" : [' + '{ "firstName":"John" , "lastName":"Doe" },' + '{ "firstName":"Anna" , "lastName":"Smith" },' + '{ "firstName":"Peter" , "lastName":"Jones" } ]}';Then, use the JaScript built-in function JSON.parse() to convert the string into a JaScript object:
var obj = JSON.parse(text);Finally, use the new JaScript object in your page:
Exampledocument.getElementById("demo").innerHTML = obj.employees[1].firstName + " " + obj.employees[1].lastName;
Try it Yourself »
Full JSON TutorialThis has been a short description of JSON.
For a full JSON tutorial go to W3Schools JSON Tutorial.
❮ Previous Next ❯ ★ +1 Track your progress - it's free! Log in Sign Up