JavaScript Object Notation (JSON) String Conversion to object

Source: Internet
Author: User

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 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.