JSON.parse 函数 (JavaScript)

2023-05-20,,

将 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 ("<br/>"); var newArr = JSON.parse(str); while (newArr.length > 0) {
document.write(newArr.pop() + "<br/>");
} // 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

要求

在以下文档模式中受到支持:Internet Explorer 8 标准模式、Internet Explorer 9 标准模式、Internet Explorer 10 标准模式、Internet Explorer 11 标准模式。此外,也在应用商店应用(Windows 8 和 Windows Phone 8.1)中受支持。请参阅 版本信息。

在以下文档模式中不受支持:Quirks、Internet Explorer 6 标准模式、Internet Explorer 7 标准模式。

请参阅

JSON.parse 函数 (JavaScript)的相关教程结束。

《JSON.parse 函数 (JavaScript).doc》

下载本文的Word格式文档,以方便收藏与打印。