javascript - 什么是 JSON 安全对象?

标签 javascript json

在凯尔辛普森的书中 You Don't Know JS: this & Object Prototypes , 他写了这篇关于如何复制对象的主题:

One subset solution is that objects which are JSON-safe (that is, can be serialized to a JSON string and then re-parsed to an object with the same structure and values) can easily be duplicated with:

var newObj = JSON.parse( JSON.stringify( someObj ) );

Of course, that requires you to ensure your object is JSON safe. For some situations, that's trivial. For others, it's insufficient.

什么是“JSON 安全”对象?我用 JavaScript 运行了一些测试,到目前为止,大多数东西(数组、数字、字符串、对象)都可以使用上面的行复制,除了方法(foo.bar),当试图复制一个方法,undefined 被插入到复制对象中方法的位置。

最佳答案

要让 foo<=> JSON.parse(JSON.stringify(foo)) 为真,我们必须能够表示 fooJSON format .

JSON 只支持:

Number: a signed decimal number that may contain a fractional part and may use exponential E notation, but cannot include non-numbers like NaN. The format makes no distinction between integer and floating-point. JavaScript uses a double-precision floating-point format for all its numeric values, but other languages implementing JSON may encode numbers differently.


String: a sequence of zero or more Unicodecharacters. Strings are delimited with double-quotation marks and support a backslash escaping syntax.


Boolean: either of the values true or false


Array: an ordered list of zero or more values, each of which may be of any type. Arrays use square bracket notation with elements being comma-separated.


Object: an unordered collection of name/value pairs where the names (also called keys) are strings. Since objects are intended to represent associative arrays,[12] it is recommended, though not required,[13] that each key is unique within an object. Objects are delimited with curly brackets and use commas to separate each pair, while within each pair the colon ':' character separates the key or name from its value.


null: An empty value, using the word null


在javascript中,JSON safe object的概念基本上是指可以无损地用JSON格式表示的javascript对象。

关于javascript - 什么是 JSON 安全对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46416370/

相关文章:

java - Neo4J 和 Spring 返回空关系

java - 如何检索特定的 Json 对象,无论其在 Json 中的深度如何?

javascript - Angular 中的路由

带有广度优先搜索的 JavaScript 二叉树

Javascript动态插入DOM元素自动触发onclick事件

javascript - ZingChart X 轴标签显示为数字而不是字符串

java - 需要构建实用程序,该实用程序将使用 JSON SIMPLE api 根据嵌套 JSON 文件中的键检索值

javascript - 使用 ui.router AngularJs 进行路由

javascript - 如何根据条件将一个JS数组存储到不同的数组中

java - 使用同一张表的不同项目的特定配置