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?
-
1There's no such thing as a json object. Are you trying to serialize values into json, or are you trying to pass values into a JavaScript object?Adam Rackis– Adam Rackis2012年06月06日 18:34:27 +00:00Commented Jun 6, 2012 at 18:34
-
I want to be able to create a json file to store the values of the checkboxes so the users choices are saved in a cookie. I am new to json so I don't know whicH i wantdaniel langer– daniel langer2012年06月06日 18:36:41 +00:00Commented Jun 6, 2012 at 18:36
-
3possible duplicate of storing and retrieving json objects to / from a cookie, serialize form to json and store in the cookie and How do I store this JSON object as a cookie and than read it in vanilla javascript?Bergi– Bergi2012年06月06日 19:03:06 +00:00Commented Jun 6, 2012 at 19:03
-
IE7 and below need the JSON2.js library and do not support this API natively. caniuse.com/jsonRitsaert Hornstra– Ritsaert Hornstra2013年03月13日 15:22:08 +00:00Commented Mar 13, 2013 at 15:22
2 Answers 2
I think you can use JSON.stringify:
// after your each loop
JSON.stringify(values);
8 Comments
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:
1 Comment
Explore related questions
See similar questions with these tags.