Javascript - .toJSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2819375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - .toJSON
提问by SoftwareGeek
I am a newbie to JSON & hence I am not sure what $.toJSON(params)means.
我是 JSON 的新手,因此我不确定这$.toJSON(params)意味着什么。
Please explain what this does.
请解释这是做什么的。
回答by Rebecca Chernoff
It could be this jQuery plugin
它可能是这个jQuery 插件
var myObj = {};
myObj.propA = "a";
myObj.propB = "b";
myObj.propC = "c";
var jsonString = $.toJSON(myObj); // same as jQuery.toJSON(myObj)
// output: '{ "propA" : "a", "propB" : "b", "propC" : "c" }'
回答by gnarf
See: http://www.json.org/js.html
见:http: //www.json.org/js.html
A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier.
var myJSONText = JSON.stringify(myObject, replacer);If the
stringifymethod sees an object that contains atoJSONmethod, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation.The stringifier method can take an optional array of strings. These strings are used to select the properties that will be included in the JSON text.
The stringifier method can take an optional
replacerfunction. It will be called after thetoJSONmethod (if there is one) on each of the values in the structure. It will be passed each key and value as parameters, and this will be bound to object holding the key. The value returned will be stringified.
JSON stringifier 则相反,将 JavaScript 数据结构转换为 JSON 文本。JSON 不支持循环数据结构,因此请注意不要为 JSON 字符串化符提供循环结构。
var myJSONText = JSON.stringify(myObject, replacer);如果该
stringify方法看到一个包含方法的对象toJSON,它会调用该方法,并将返回的值字符串化。这允许对象确定自己的 JSON 表示。stringifier 方法可以采用可选的字符串数组。这些字符串用于选择将包含在 JSON 文本中的属性。
stringifier 方法可以采用可选
replacer函数。它将toJSON在结构中的每个值的方法(如果有)之后调用。它将每个键和值作为参数传递,这将绑定到持有键的对象。返回的值将被字符串化。
So if you have a $.toJSON()method, it could be a badly implemented functionto "stringify", or it could be a method that returns the "JSON Representation" of $
所以如果你有一个$.toJSON()方法,它可能是一个错误实现的“字符串化”函数,或者它可能是一个返回“JSON 表示”的方法$
回答by Quentin
It passes the variable paramsas an argument to the method named toJSONattached to the object stored in the (unhelpfully named) variable $.
它将变量params作为参数传递给toJSON附加到存储在(无用的命名)变量中的对象的命名方法$。
Based on the name, it probably converts the contents of the paramsvariable to a String formatted according to the JSON specification.
根据名称,它可能将params变量的内容转换为根据JSON 规范格式化的字符串。

