如何将JavaScript对象编码为JSON?

时间:2022-12-01 16:31:02

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?

有人知道解决方案吗?

2 个解决方案

#1


102  

I think you can use JSON.stringify:

我想你可以用json。stringify:

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

#2


23  

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类型有:对象、字符串、数字、数组、true、false和null。

Some JSON resources:

一些JSON资源:

#1


102  

I think you can use JSON.stringify:

我想你可以用json。stringify:

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

#2


23  

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类型有:对象、字符串、数字、数组、true、false和null。

Some JSON resources:

一些JSON资源: