How do I encode a JavaScript object as JSON?

daniel langer picture daniel langer · Jun 6, 2012 · Viewed 240.3k times · Source

Is there a good way to encode a JavaScript object as 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).

Does anyone know a solution?

Answer

mimiz picture mimiz · Jun 6, 2012

I think you can use JSON.stringify:

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