WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript JSON


JSON is the format used to store and transfer data.

JSON is often used by servers to pass data to web pages.

  • JSON full name in English J ava S cript O bject N otation
  • JSON is a lightweight data exchange format.
  • JSON is an independent language *
  • JSON is easy to understand.
* 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.

Examples in JS

Example


{
"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]
}

JSON formatted as JavaScript object

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

Because they are similar, JavaScript programs can easily convert JSON data into JavaScript objects.


JSON syntax rules

  • The data is a key /value pair.
  • Data is separated by commas.
  • Braces save objects
  • Square brackets hold array

JSON data-one name corresponds to one value

JSON data is formatted as key /value pairs, just like JavaScript object attributes.

The key /value pair includes the field name (in double quotes), followed by a colon, and then the value:

Convert JSON string to JavaScript object

Usually we read JSON data from the server and display the data in a web page.

For simplicity, we set the JSON string directly on our webpage (you can also read our JSON tutorial ):

First, create a JavaScript string, which will be JSON-formatted data:

var text = ' {"sites": [ ' + ' {"name": "welookups", "url": "www.welookups.com"} , ' + ' {"name": "Google", "url": "www.google.com"} , ' + ' {"name": "amazon", "url": "www.amazon.com"} ]} ' ;

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

var obj = JSON.parse (text);

Finally, use the new JavaScript object in your page:

Examples

var text = '{ "sites" : [' + '{ "name":"welookups" , "url":"www.welookups.com" },' + '{ "name":"Google" , "url":"www.google.com" },' + '{ "name":"amazon" , "url":"www.amazon.com" } ]}'; obj = JSON.parse(text); document.getElementById("demo").innerHTML = obj.sites[1].name + " " + obj.sites[1].url;

Related functions

Function Description
JSON.parse () For converting a JSON string into a JavaScript object.
JSON.stringify () For converting JavaScript values to JSON strings.