25

I want to build a JSON string programmatically. The end product should be something like this:

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 do something like this:

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

I wouldn't even mind building that array and then converting it to JSON.

Ajay2707
  • 5,690
  • 6
  • 40
  • 58
Kenneth Vogt
  • 985
  • 4
  • 12
  • 28
  • use JSON.stringify() http://ajaxify.com/run/json/ – Larry Battle May 11 '12 at 23:11
  • 5
    possible duplicate of [Convert JS object to JSON string](http://stackoverflow.com/questions/4162749/convert-js-object-to-json-string) and [possibly others](http://stackoverflow.com/search?q=javascript+convert+to+json). – Felix Kling May 11 '12 at 23:12
  • 2
    http://stackoverflow.com/questions/558518/how-to-serialise-on-object-to-json-in-javascript – Ryan Quinn May 11 '12 at 23:12
  • Note that you should not use non-numerical properties with arrays, use a plain object instead. – Felix Kling May 11 '12 at 23:14
  • Of course you can build the object however you want to and it seems you already know how to do this. It's just that how to convert an array or object to JSON was asked before and there is no point in repeating answers. Anyways, the community decides... If your question is more about how to create an object dynamically, then you should make this more clear. The title ask for how to convert to JSON. – Felix Kling May 11 '12 at 23:33
  • Felix, please edit the title to something more appropriate. – Kenneth Vogt May 11 '12 at 23:39

2 Answers2

55

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
14

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"}"
rdougan
  • 7,217
  • 2
  • 34
  • 63