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: Use the JSON. stringify() Method You can use the JSON. stringify() method to easily convert a JavaScript object a JSON string.
Encode a JSON Object - to String − Simple encoding. Encode a JSON Object - Streaming − Output can be used for streaming. Encode a JSON Object - Using Map − Encoding by preserving the order. Encode a JSON Object - Using Map and Streaming − Encoding by preserving the order and to stream.
var obj = new Object(); obj.name = "Raj"; obj. age = 32; obj. married = false; //convert object to json string var string = JSON. stringify(obj); //convert string to Json Object console.
As below, yes you could.
I think you can use JSON.stringify:
// after your each loop JSON.stringify(values);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With