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"}"
链接地址: http://www.djcxy.com/p/46274.html