English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
JSON is used for data exchange with web servers. When data is received from a web server, it is always a string.
The JSON.parse() method parses a JSON string to construct JavaScript values or the object described by the string.
Syntax:
JSON.parse(text, reviver)
The first parameter specifies the string to be parsed as JSON.
The optional second parameter specifies a function to check each property before the return value.
Suppose we receive the following text from the web server:
22, "city":"New Delhi"
Using the JSON.parse() method, we can convert JSON text to a JavaScript object:
22, "city":"New Delhi"Test it out‹/›
You can use AJAX requests to request JSON from the server.
If the response from the server is written in JSON format, the string can be parsed into a JavaScript object.
The following example requests the filedemo.jsonand parse the response:
var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { var myObj = JSON.parse(this.responseText); document.getElementById("output").innerHTML = myObj.name; } }; httpRequest.open("GET", "demo.json", true); httpRequest.send();Test it out‹/›
JSON.parse() is used on JSON derived from arrays, which will return a JavaScript array instead of a JavaScript object.
The following example requests the filejson_array.txtand parse the response:
var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { var myArr = JSON.parse(this.responseText); document.getElementById("output").innerHTML = myArr[0]; } }; httpRequest.open("GET", "json_array.txt", true); httpRequest.send();Test it out‹/›
Date objects are not allowed in JSON.
If you need to include dates, write them as strings and then convert them back to date objects later.
var myJSON = '{"name":"Seagull", "birth":"1997-11-10", "city":"New Delhi"}'; var myObj = JSON.parse(myJSON); myObj.birth = new Date(myObj.birth); document.getElementById("output").innerHTML = myObj.name + " DOB is " + myObj.birth;Test it out‹/›
Note: Converting a string into a local object is calledParsing, and converts a local object into a format that can be transmitted over the network.Stringis calledStringification.