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

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.

Read more here: Source link