82

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?

Brett DeWoody
63.3k31 gold badges145 silver badges192 bronze badges
asked Jun 6, 2012 at 18:26
4

2 Answers 2

158

I think you can use JSON.stringify:

// after your each loop
JSON.stringify(values);
Alexander
23.5k11 gold badges65 silver badges74 bronze badges
answered Jun 6, 2012 at 18:31
Sign up to request clarification or add additional context in comments.

8 Comments

I put this in an alert() but nothing appears
@daniellanger - based on your comment, this is the answer. You'll need to do some debugging to see why things aren't showing up
so how can I save this to a file/ store it as a cookie?
IE 10 is giving: JavaScript runtime error: 'JSON' is undefined
|
44

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:

answered Jun 6, 2012 at 18:48

1 Comment

Well, they are called "objects" in javascript. But yes, boolean values can be represented in JSON.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.