JSON.parse、JSON.stringify
JSON.parse()
方法用来解析JSON字符串,构造由字符串描述的JavaScript值或对象。提供可选的 reviver 函数用以在返回之前对所得到的对象执行变换(操作)。
1 JSON.parse(text[, reviver])
text
- 要被解析成 JavaScript 值的字符串,关于JSON的语法格式,请参考:
JSON
。 reviver
可选- 转换器, 如果传入该参数(函数),可以用来修改解析生成的原始值,调用时机在 parse 函数返回之前。
返回值
Object
类型, 对应给定 JSON 文本的对象/值。
异常
若传入的字符串不符合 JSON 规范,则会抛出 SyntaxError
异常。
示例
使用 JSON.parse()
1 JSON.parse('{}'); // {} 2 JSON.parse('true'); // true 3 JSON.parse('"foo"'); // "foo" 4 JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] 5 JSON.parse('null'); // null
使用 reviver
函数
如果指定了 reviver
函数,则解析出的 JavaScript 值(解析值)会经过一次转换后才将被最终返回(返回值)。更具体点讲就是:解析值本身以及它所包含的所有属性,会按照一定的顺序(从最最里层的属性开始,一级级往外,最终到达顶层,也就是解析值本身)分别的去调用 reviver
函数,在调用过程中,当前属性所属的对象会作为 this
值,当前属性名和属性值会分别作为第一个和第二个参数传入 reviver
中。如果 reviver
返回 undefined
,则当前属性会从所属对象中删除,如果返回了其他值,则返回的值会成为当前属性新的属性值。
当遍历到最顶层的值(解析值)时,传入 reviver
函数的参数会是空字符串 ""
(因为此时已经没有真正的属性)和当前的解析值(有可能已经被修改过了),当前的 this
值会是 {"": 修改过的解析值}
,在编写 reviver
函数时,要注意到这个特例。(这个函数的遍历顺序依照:从最内层开始,按照层级顺序,依次向外遍历)
1 JSON.parse('{"p": 5}', function (k, v) { 2 if(k === '') return v; // 如果到了最顶层,则直接返回属性值, 3 return v * 2; // 否则将属性值变为原来的 2 倍。 4 }); // { p: 10 } 5 6 JSON.parse('{"1": 1, "2": 2,"3": {"4": 4, "5": {"6": 6}}}', function (k, v) { 7 console.log(k); // 输出当前的属性名,从而得知遍历顺序是从内向外的, 8 // 最后一个属性名会是个空字符串。 9 return v; // 返回原始属性值,相当于没有传递 reviver 参数。 10 }); 11 12 // 1 13 // 2 14 // 4 15 // 6 16 // 5 17 // 3 18 // ""
JSON.parse()
不允许用逗号作为结尾
1 // both will throw a SyntaxError 2 JSON.parse("[1, 2, 3, 4, ]"); 3 JSON.parse('{"foo" : 1, }');
Polyfill
1 // From https://github.com/douglascrockford/JSON-js/blob/master/json2.js 2 if (typeof JSON.parse !== "function") { 3 var rx_one = /^[\],:{}\s]*$/; 4 var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g; 5 var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; 6 var rx_four = /(?:^|:|,)(?:\s*\[)+/g; 7 var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; 8 JSON.parse = function(text, reviver) { 9 10 // The parse method takes a text and an optional reviver function, and returns 11 // a JavaScript value if the text is a valid JSON text. 12 13 var j; 14 15 function walk(holder, key) { 16 17 // The walk method is used to recursively walk the resulting structure so 18 // that modifications can be made. 19 20 var k; 21 var v; 22 var value = holder[key]; 23 if (value && typeof value === "object") { 24 for (k in value) { 25 if (Object.prototype.hasOwnProperty.call(value, k)) { 26 v = walk(value, k); 27 if (v !== undefined) { 28 value[k] = v; 29 } else { 30 delete value[k]; 31 } 32 } 33 } 34 } 35 return reviver.call(holder, key, value); 36 } 37 38 39 // Parsing happens in four stages. In the first stage, we replace certain 40 // Unicode characters with escape sequences. JavaScript handles many characters 41 // incorrectly, either silently deleting them, or treating them as line endings. 42 43 text = String(text); 44 rx_dangerous.lastIndex = 0; 45 if (rx_dangerous.test(text)) { 46 text = text.replace(rx_dangerous, function(a) { 47 return ( 48 "\\u" + 49 ("0000" + a.charCodeAt(0).toString(16)).slice(-4) 50 ); 51 }); 52 } 53 54 // In the second stage, we run the text against regular expressions that look 55 // for non-JSON patterns. We are especially concerned with "()" and "new" 56 // because they can cause invocation, and "=" because it can cause mutation. 57 // But just to be safe, we want to reject all unexpected forms. 58 59 // We split the second stage into 4 regexp operations in order to work around 60 // crippling inefficiencies in IE's and Safari's regexp engines. First we 61 // replace the JSON backslash pairs with "@" (a non-JSON character). Second, we 62 // replace all simple value tokens with "]" characters. Third, we delete all 63 // open brackets that follow a colon or comma or that begin the text. Finally, 64 // we look to see that the remaining characters are only whitespace or "]" or 65 // "," or ":" or "{" or "}". If that is so, then the text is safe for eval. 66 67 if ( 68 rx_one.test( 69 text 70 .replace(rx_two, "@") 71 .replace(rx_three, "]") 72 .replace(rx_four, "") 73 ) 74 ) { 75 76 // In the third stage we use the eval function to compile the text into a 77 // JavaScript structure. The "{" operator is subject to a syntactic ambiguity 78 // in JavaScript: it can begin a block or an object literal. We wrap the text 79 // in parens to eliminate the ambiguity. 80 81 j = eval("(" + text + ")"); 82 83 // In the optional fourth stage, we recursively walk the new structure, passing 84 // each name/value pair to a reviver function for possible transformation. 85 86 return (typeof reviver === "function") ? 87 walk({ 88 "": j 89 }, "") : 90 j; 91 } 92 93 // If the text is not JSON parseable, then a SyntaxError is thrown. 94 95 throw new SyntaxError("JSON.parse"); 96 }; 97 }
JSON.stringify()
方法将一个 JavaScript 对象或值转换为 JSON 字符串,如果指定了一个 replacer 函数,则可以选择性地替换值,或者指定的 replacer 是数组,则可选择性地仅包含数组指定的属性。
语法
1 JSON.stringify(value[, replacer [, space]])
参数
value
- 将要序列化成 一个 JSON 字符串的值。
replacer
可选- 如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理;如果该参数是一个数组,则只有包含在这个数组中的属性名才会被序列化到最终的 JSON 字符串中;如果该参数为 null 或者未提供,则对象所有的属性都会被序列化。
space
可选- 指定缩进用的空白字符串,用于美化输出(pretty-print);如果参数是个数字,它代表有多少的空格;上限为10。该值若小于1,则意味着没有空格;如果该参数为字符串(当字符串长度超过10个字母,取其前10个字母),该字符串将被作为空格;如果该参数没有提供(或者为 null),将没有空格。
返回值
- 一个表示给定值的JSON字符串。
异常
- Throws a
TypeError
("cyclic object value") exception when a circular reference is found. - Throws a
TypeError
("BigInt value can't be serialized in JSON") when trying to stringify aBigInt
value.
描述
JSON.stringify()
将值转换为相应的JSON格式:
- 转换值如果有 toJSON() 方法,该方法定义什么值将被序列化。
- 非数组对象的属性不能保证以特定的顺序出现在序列化后的字符串中。
- 布尔值、数字、字符串的包装对象在序列化过程中会自动转换成对应的原始值。
undefined
、任意的函数以及 symbol 值,在序列化过程中会被忽略(出现在非数组对象的属性值中时)或者被转换成null
(出现在数组中时)。函数、undefined 被单独转换时,会返回 undefined,如JSON.stringify(function(){})
orJSON.stringify(undefined)
.- 对包含循环引用的对象(对象之间相互引用,形成无限循环)执行此方法,会抛出错误。
- 所有以 symbol 为属性键的属性都会被完全忽略掉,即便
replacer
参数中强制指定包含了它们。 - Date 日期调用了 toJSON() 将其转换为了 string 字符串(同Date.toISOString()),因此会被当做字符串处理。
- NaN 和 Infinity 格式的数值及 null 都会被当做 null。
- 其他类型的对象,包括 Map/Set/WeakMap/WeakSet,仅会序列化可枚举的属性。
示例
使用 JSON.stringify
1 JSON.stringify({}); // '{}' 2 JSON.stringify(true); // 'true' 3 JSON.stringify("foo"); // '"foo"' 4 JSON.stringify([1, "false", false]); // '[1,"false",false]' 5 JSON.stringify({ x: 5 }); // '{"x":5}' 6 7 JSON.stringify({x: 5, y: 6}); 8 // "{"x":5,"y":6}" 9 10 JSON.stringify([new Number(1), new String("false"), new Boolean(false)]); 11 // '[1,"false",false]' 12 13 JSON.stringify({x: undefined, y: Object, z: Symbol("")}); 14 // '{}' 15 16 JSON.stringify([undefined, Object, Symbol("")]); 17 // '[null,null,null]' 18 19 JSON.stringify({[Symbol("foo")]: "foo"}); 20 // '{}' 21 22 JSON.stringify({[Symbol.for("foo")]: "foo"}, [Symbol.for("foo")]); 23 // '{}' 24 25 JSON.stringify( 26 {[Symbol.for("foo")]: "foo"}, 27 function (k, v) { 28 if (typeof k === "symbol"){ 29 return "a symbol"; 30 } 31 } 32 ); 33 34 35 // undefined 36 37 // 不可枚举的属性默认会被忽略: 38 JSON.stringify( 39 Object.create( 40 null, 41 { 42 x: { value: 'x', enumerable: false }, 43 y: { value: 'y', enumerable: true } 44 } 45 ) 46 ); 47 48 // "{"y":"y"}"
replacer参数
replacer 参数可以是一个函数或者一个数组。作为函数,它有两个参数,键(key)和值(value),它们都会被序列化。
在开始时, replacer
函数会被传入一个空字符串作为 key
值,代表着要被 stringify
的这个对象。随后每个对象或数组上的属性会被依次传入。
函数应当返回JSON字符串中的value, 如下所示:
- 如果返回一个
Number
, 转换成相应的字符串作为属性值被添加入 JSON 字符串。 - 如果返回一个
String
, 该字符串作为属性值被添加入 JSON 字符串。 - 如果返回一个
Boolean
, "true" 或者 "false" 作为属性值被添加入 JSON 字符串。 - 如果返回任何其他对象,该对象递归地序列化成 JSON 字符串,对每个属性调用 replacer 方法。除非该对象是一个函数,这种情况将不会被序列化成 JSON 字符串。
- 如果返回 undefined,该属性值不会在 JSON 字符串中输出。
注意: 不能用 replacer 方法,从数组中移除值(values),如若返回 undefined 或者一个函数,将会被 null 取代。
例子(function)
1 function replacer(key, value) { 2 if (typeof value === "string") { 3 return undefined; 4 } 5 return value; 6 } 7 8 var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7}; 9 var jsonString = JSON.stringify(foo, replacer);
JSON序列化结果为 {"week":45,"month":7}
.
例子(array)
如果 replacer
是一个数组,数组的值代表将被序列化成 JSON 字符串的属性名。
1 JSON.stringify(foo, ['week', 'month']); 2 // '{"week":45,"month":7}', 只保留 “week” 和 “month” 属性值。
space
参数
space
参数用来控制结果字符串里面的间距。如果是一个数字, 则在字符串化时每一级别会比上一级别缩进多这个数字值的空格(最多10个空格);如果是一个字符串,则每一级别会比上一级别多缩进该字符串(或该字符串的前10个字符)。
1 JSON.stringify({ a: 2 }, null, " "); // '{\n "a": 2\n}'
使用制表符(\t)来缩进:
1 JSON.stringify({ uno: 1, dos : 2 }, null, '\t') 2 // '{ \ 3 // "uno": 1, \ 4 // "dos": 2 \ 5 // }'
toJSON 方法
如果一个被序列化的对象拥有 toJSON
方法,那么该 toJSON
方法就会覆盖该对象默认的序列化行为:不是该对象被序列化,而是调用 toJSON
方法后的返回值会被序列化,例如:
1 var obj = { 2 foo: 'foo', 3 toJSON: function () { 4 return 'bar'; 5 } 6 }; 7 JSON.stringify(obj); // '"bar"' 8 JSON.stringify({x: obj}); // '{"x":"bar"}'
JSON.stringify
用作 JavaScript
注意 JSON 不是 JavaScript 严格意义上的子集,在 JSON 中不需要省略两条终线(Line separator 和 Paragraph separator),但在 JavaScript 中需要被省略。因此,如果 JSON 被用作 JSONP 时,下面方法可以使用:
1 function jsFriendlyJSONStringify (s) { 2 return JSON.stringify(s). 3 replace(/\u2028/g, '\\u2028'). 4 replace(/\u2029/g, '\\u2029'); 5 } 6 7 var s = { 8 a: String.fromCharCode(0x2028), 9 b: String.fromCharCode(0x2029) 10 }; 11 try { 12 eval('(' + JSON.stringify(s) + ')'); 13 } catch (e) { 14 console.log(e); // "SyntaxError: unterminated string literal" 15 } 16 17 // No need for a catch 18 eval('(' + jsFriendlyJSONStringify(s) + ')'); 19 20 // console.log in Firefox unescapes the Unicode if 21 // logged to console, so we use alert 22 alert(jsFriendlyJSONStringify(s)); // {"a":"\u2028","b":"\u2029"}
使用 JSON.stringify 结合 localStorage 的例子
一些时候,你想存储用户创建的一个对象,并且,即使在浏览器被关闭后仍能恢复该对象。下面的例子是 JSON.stringify
适用于这种情形的一个样板:
1 // 创建一个示例数据 2 var session = { 3 'screens' : [], 4 'state' : true 5 }; 6 session.screens.push({"name":"screenA", "width":450, "height":250}); 7 session.screens.push({"name":"screenB", "width":650, "height":350}); 8 session.screens.push({"name":"screenC", "width":750, "height":120}); 9 session.screens.push({"name":"screenD", "width":250, "height":60}); 10 session.screens.push({"name":"screenE", "width":390, "height":120}); 11 session.screens.push({"name":"screenF", "width":1240, "height":650}); 12 13 // 使用 JSON.stringify 转换为 JSON 字符串 14 // 然后使用 localStorage 保存在 session 名称里 15 localStorage.setItem('session', JSON.stringify(session)); 16 17 // 然后是如何转换通过 JSON.stringify 生成的字符串,该字符串以 JSON 格式保存在 localStorage 里 18 var restoredSession = JSON.parse(localStorage.getItem('session')); 19 20 // 现在 restoredSession 包含了保存在 localStorage 里的对象 21 console.log(restoredSession);