简体   繁体   English

直接使用JSON.stringify Javascript对象是一种好习惯吗?

[英]Is it a good practice to directly JSON.stringify Javascript objects?

I have data-structures that are defined as Javascript objects. 我有定义为Javascript对象的数据结构。 I like to stringify them to send over network. 我喜欢将它们分类为通过网络发送。 Merely calling JSON.stringify() on them seems to work. JSON.stringify()它们调用JSON.stringify()似乎有效。 But is it a good practice? 但这是一个好习惯吗?

Are there any special cases where this may break (for example static methods?) 是否有任何可能会中断的特殊情况(例如静态方法?)

If you just send data, and not functions, it will work fine. 如果您只是发送数据,而不发送功能,它将正常工作。 But JSON can only carry values - not functions . 但是JSON只能带有 ,而不能带有函数 Older browsers (< IE8) doesn't have the JSON object natively, so you will have to provide a fallback solution (frameworks like jQuery implements a fallback automatically). 较旧的浏览器(<IE8)本身没有JSON对象,因此您必须提供一个后备解决方案(jQuery之类的框架会自动实现后备)。

JSON is a subset of JS, so from that standpoint, it's 100% fine. JSON是JS的子集,因此从这个角度来看,它是100%好的。

JSON is also intended to be converted into JS to be operated on, and converted back, to be sent out, or stored. JSON还打算转换为JS,以便对其进行操作,转换回,发送或存储。

So turning an object into JSON is part of the intended purpose, rather than having to write all JSON by hand. 因此,将对象转换为JSON是预期目的的一部分,而不是必须手动编写所有JSON。

In terms of special cases, JSON can contain no functions, no circular references... nothing other than strings, numbers and booleans, inside of nested objects and arrays. 在特殊情况下,JSON不能在嵌套对象和数组内部包含任何函数,任何循环引用……除了字符串,数字和布尔值之外,什么都没有。

If that's already the format your data is in, you're done. 如果这已经是您数据所使用的格式,那么您就完成了。

IE6 and 7 don't have native JSON support. IE6和7没有本机JSON支持。
However, json2.js is the file from Douglas Crockford which all of the native implementations are based on. 但是,json2.js是来自Douglas Crockford的文件,所有本机实现都基于json2.js。
If !window.JSON then load that file, and it will work just fine, in OldIE. 如果!window.JSON然后加载该文件,它将在OldIE中正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM