Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I encode a JavaScript object as JSON?

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?

like image 367
daniel langer Avatar asked Jun 06 '12 18:06

daniel langer


People also ask

How would you convert an object to JSON in JavaScript?

Answer: Use the JSON. stringify() Method You can use the JSON. stringify() method to easily convert a JavaScript object a JSON string.

How do I encode a JSON object?

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.

How do you create a JSON in JavaScript?

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.

Can you write JavaScript in JSON?

As below, yes you could.


1 Answers

I think you can use JSON.stringify:

// after your each loop JSON.stringify(values); 
like image 194
mimiz Avatar answered Sep 18 '22 10:09

mimiz