How to encode JavaScript object as JSON?

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

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

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

I want to pass these values ​​to a JSON object in order to save in a cookie to display the table (columns will be added according to what the user disconnects).

Does anyone know a solution?

+48
json javascript jquery hashtable checkbox
Jun 06 '12 at 18:26
source share
2 answers

I think you can use JSON.stringify :

 // after your each loop JSON.stringify(values); 
+99
Jun 06 '12 at 18:31
source share

All major browsers now include built-in JSON encoding / decoding.

 // 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); 

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

 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 .

Some JSON resources:

+23
Jun 06 '12 at 18:48
source share



All Articles