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.
You could do a similar thing with objects:
and then you could use the
JSON.stringifymethod to turn that object into a JSON string.will show:
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.