JavaScript 对象表示法 (JSON) 字符串转换为对象

以下示例使用 JSON.parse 将 JSON 字符串转换成对象。

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.stringify 将数组转换成 JSON 字符串,然后使用 JSON.parse 将该字符串还原成数组。

var arr = ["a""b""c"]; 
var str = JSON.stringify(arr); 
document.write(str); 
document.write ("
"
);    var newArr = JSON.parse(str);    while (newArr.length > 0{      document.write(newArr.pop() + "
"
);  }    // Output:  var arr = ["a""b""c"];  var str = JSON.stringify(arr);  document.write(str);  document.write ("
"
);    var newArr = JSON.parse(str);    while (newArr.length > 0{      document.write(newArr.pop() + "
"
);  }    // Output:  ["a","b","c"]  c  b  a

reviver 函数通常用于将国际标准化组织 (ISO) 日期字符串的 JSON 表示形式转换为协调世界时 (UTC) 格式 Date 对象。

此示例使用 JSON.parse 来反序列化 ISO 格式的日期字符串。 dateReviver 函数为格式为 ISO 日期字符串的成员返回 Date 对象。

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 

你可能感兴趣的:(javascript,json)