JSON. parseConverts 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); // Output: Aaberg, Jesper
JSON. stringifyConvert the array to a JSON string and then useJSON. parseReturns the string to an array.
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/>"); } // Output: 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/>"); } // Output: ["a","b","c"] c b a
The reviver function is generally used to convert the JSON representation of an ISO Date string to a Date object in Coordinated Universal Time (UTC) format.
In this example, JSON. parse is used to deserialize date strings in ISO format. The dateReviver function returns the Date object for members of Date strings in ISO format.
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; }; // Output: // Thu, 25 Dec 2008 12:00:00 UTC