JSON.parse 函数
JavaScript
JSON.parse 函数 (JavaScript)
将 JavaScript 对象表示法 (JSON) 字符串转换为对象。
JSON.parse(text [, reviver])
示例
将 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
将该字符串还原成数组。
- 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
对象。
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 应用商店 应用程序中也支持此项。请参阅 版本信息。
在以下文档模式中不受支持:Quirks、Internet Explorer 6 标准模式、Internet Explorer 7 标准模式。
请参见