简体   繁体   English

如何在javascript / jquery中构建json字符串?

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

I would like to build a json string programmatically. 我想以编程方式构建一个json字符串。 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. 我甚至不介意构建该数组然后转换为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. 然后你可以使用JSON.stringify方法将该对象转换为JSON字符串。

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). 这种方法本身内置于所有现代浏览器中(即使IE8远非现代浏览器,IE8也支持它)。 And if you need to support some legacy browsers you could include the json2.js script. 如果您需要支持一些旧版浏览器,可以包含json2.js脚本。

Create a normal object: 创建一个普通对象:

var o = {
    first_name: 'Robert',
    last_name: 'Dougan'
};

And then use JSON.stringify to make it a string: 然后使用JSON.stringify使其成为一个字符串:

var string = JSON.stringify(o); //"{"first_name":"Robert","last_name":"Dougan"}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM