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

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?

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.

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"}"


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Map vs Object in JavaScript

Similar Posts