Converts a JavaScript Object Notation (JSON) string into an object.
SyntaxJSON.parse( text [ , reviver] )
An object or array.
ExamplesThe following example uses JSON.parse to convert a JSON string to an object.
var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname);
The following example shows how to convert an array to a JSON string by using JSON.stringify , and then convert the string back to an array by using JSON.parse.
var arr = ["a", "b", "c"];
var str = JSON.stringify(arr);
document.write(str);
document.write ("<br/>");
var newArr = JSON.parse(str);
while (newArr.length > 0) {
document.write(newArr.pop() + "<br/>");
}
var arr = ["a", "b", "c"];
var str = JSON.stringify(arr);
document.write(str);
document.write ("<br/>");
var newArr = JSON.parse(str);
while (newArr.length > 0) {
document.write(newArr.pop + "<br/>");
}
["a","b","c"]
c
b
a
The reviver function is often used to transform JSON representation of International Organization for Standardization (ISO) date strings into Coordinated Universal Time (UTC) format Date objects.
This example uses JSON.parse to deserialize an ISO-formatted date string. The dateReviver
function returns Date
objects for members that are formatted like ISO date strings.
var jsontext = '{ "hiredate": "2008-01-01T12:00:00Z", "birthdate": "2008-12-25T12:00:00Z" }';
var dates = JSON.parse(jsontext, dateReviver);
document.write(dates.birthdate.toUTCString());
function dateReviver(key, value) {
var a;
if (typeof value === 'string') {
a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
};
Exceptions
If this function provokes a JavaScript parser error (such as "SCRIPT1014: Invalid character", the input text does not comply with JSON syntax. To correct the error, do one of the following:
Microsoft Developer Network: Article
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4