JavaScript JSON parse() Method
❮
JSON Object
❯
Example
Parse a string (written in JSON format) and return a JavaScript object:
var obj = JSON.parse('{"firstName":"John", "lastName":"Doe"}');
Try it Yourself »
More "Try it Yourself" examples below.
Description
The JSON.parse() method parses a string and returns a JavaScript object.
The string has to be written in JSON format.
The JSON.parse() method can optionally transform the result with a function.
Browser Support
The numbers in the table specify the first browser version that fully supports the method.
Method | |||||
---|---|---|---|---|---|
parse() | 4.0 | 8.0 | 3.5 | 4.0 | 11.5 |
Syntax
JSON.parse(string, function)
Parameter Values
Parameter | Description |
---|---|
string | Required. A string written in JSON format |
reviver function | Optional. A function used to transform the result. The function is called for each item. Any nested objects are transformed before the parent.
|
Technical Details
Return Value: | A JSON Object, or Array |
---|---|
JavaScript Version: | ECMAScript 5 |
More Examples
Example
How to use the reviver function:
/*replace the value of "city" to upper case:*/
var text =
'{ "name":"John", "age":"39", "city":"New York"}';
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;
Try it Yourself »
Example
Parsing 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();
Try it Yourself »
Take a look at json_demo.txt
Related Pages
JSON Tutorial: JSON Introduction
❮
JSON Object
❯
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.