如何将 JavaScript 对象编码为 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10919965/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:34:34  来源:igfitidea点击:

How do I encode a JavaScript object as JSON?

javascriptjqueryjsoncheckboxhashtable

提问by daniel langer

Is there a good way to encode a JavaScript object as JSON?

有没有一种将 JavaScript 对象编码为 JSON 的好方法?

I have a list of key value pairs...where the name is from a checkbox, and the value is either true or false based on whether the box is checked or not:

我有一个键值对列表......其中名称来自复选框,并且根据是否选中该框,该值为真或假:

var values = {};
$('#checks :checkbox').each(function() { values[this.name]=this.checked; }); 

I want to pass these values into a JSON object so store into a cookie to render a table (Columns will be added according to what the user checks off).

我想将这些值传递到 JSON 对象中,以便存储到 cookie 中以呈现表(将根据用户检查的内容添加列)。

Does anyone know a solution?

有谁知道解决方案?

回答by mimiz

I think you can use JSON.stringify:

我认为你可以使用JSON.stringify

// after your each loop
JSON.stringify(values);

回答by vezult

All major browsers now include native JSON encoding/decoding.

所有主要浏览器现在都包含原生 JSON 编码/解码。

// To encode an object (This produces a string)
var json_str = JSON.stringify(myobject); 

// To decode (This produces an object)
var obj = JSON.parse(json_str);

Note that only valid JSON data will be encoded. For example:

请注意,只会对有效的 JSON 数据进行编码。例如:

var obj = {'foo': 1, 'bar': (function (x) { return x; })}
JSON.stringify(obj) // --> "{\"foo\":1}"

Valid JSON types are: objects, strings, numbers, arrays, true, false, and null.

有效的 JSON 类型包括:对象、字符串、数字、数组truefalse、 和null

Some JSON resources:

一些 JSON 资源: