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?
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.
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() .
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"}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With