JavaScript JSON parse() Method
- Previous Page parse()
- Next Page stringify()
- Go to the Previous Level JavaScript JSON Reference Manual
Definition and Usage
The JSON.parse() method parses the string and returns a JavaScript object.
The string must be written in JSON format.
The JSON.parse() method can choose to use a function to convert the result.
Instance
Example 1
Parse a string (written in JSON format) and return a JavaScript object:
var obj = JSON.parse('{"firstName":"Bill", "lastName":"Gates"}');
Example 2
How to use the reviver function:
/* Replace the "city" value with uppercase: */ var text = '{ "name":"Bill", "age":"19", "city":"Seattle"}'; var obj = JSON.parse(text, function (key, value) { if (key == "city") { return value.toUpperCase(); } else { return value; } }); document.getElementById("demo").innerHTML = obj.name + ", " + obj.city;
Example 3
Parse JSON received from the server:
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; } }; xmlhttp.open("GET", "json_demo.txt", true); xmlhttp.send();
Syntax
JSON.parse(string, function)
Parameter value
Parameter | Description |
---|---|
string | Required. A string written in JSON format. |
reviver function |
Optional. A function used to transform the result. This function is called for each item. Any nested objects are transformed before the parent object. If this function returns a valid value, then replace the item value with the converted value. If this function returns undefined, then remove this item. |
Technical details
Return value: | JSON object, or number. |
---|---|
JavaScript version: | ECMAScript 5 |
Browser support
The numbers in the table indicate the first browser version that fully supports this method.
Method | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
parse() | 4.0 | 8.0 | 3.5 | 4.0 | 11.5 |
Related Pages
JSON Tutorial:Introduction to JSON
- Previous Page parse()
- Next Page stringify()
- Go to the Previous Level JavaScript JSON Reference Manual