How do I encode a JavaScript object as JSON?

JavascriptJqueryJsonCheckboxHashtable

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

I think you can use JSON.stringify:

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

Solution 2 - Javascript

All major browsers now include native 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);

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:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondaniel langerView Question on Stackoverflow
Solution 1 - JavascriptmimizView Answer on Stackoverflow
Solution 2 - JavascriptvezultView Answer on Stackoverflow