Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I build a json string in javascript/jquery?

Tags:

I would like to build a json string programmatically. The end product should be something like:

var myParamsJson = {first_name: "Bob", last_name: "Smith" }; 

However I would like to do it one parameter at a time. If it were an array, I would just do something like:

var myParamsArray = []; myParamsArray["first_name"] = "Bob"; myParamsArray["last_name"] = "Smith"; 

I wouldn't even mind building that array and then converting to json. Any ideas?

like image 881
Kenneth Vogt Avatar asked May 11 '12 23:05

Kenneth Vogt


People also ask

How do I create a JSON string?

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.

What is JSON string JavaScript?

A common use of JSON is to exchange data to/from a web server. When sending data to a web server, the data has to be a string. Convert a JavaScript object into a string with JSON. stringify() .


2 Answers

You could do a similar thing with objects:

var myObj = {}; myObj["first_name"] = "Bob"; myObj["last_name"] = "Smith"; 

and then you could use the JSON.stringify method to turn that object into a JSON string.

var json = JSON.stringify(myObj); alert(json); 

will show:

{"first_name":"Bob","last_name":"Smith"} 

This method is natively built into all modern browsers (even IE8 supports it, even if IE8 is very far from being a modern browser). And if you need to support some legacy browsers you could include the json2.js script.

like image 176
Darin Dimitrov Avatar answered Sep 26 '22 00:09

Darin Dimitrov


Create a normal object:

var o = {     first_name: 'Robert',     last_name: 'Dougan' }; 

And then use JSON.stringify to make it a string:

var string = JSON.stringify(o); //"{"first_name":"Robert","last_name":"Dougan"}" 
like image 31
rdougan Avatar answered Sep 25 '22 00:09

rdougan