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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10559660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:52:03  来源:igfitidea点击:

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

javascriptjson

提问by Kenneth Vogt

I would like to build a json string programmatically. The end product should be something like:

我想以编程方式构建一个 json 字符串。最终产品应该是这样的:

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?

我什至不介意构建该数组然后转换为 json。有任何想法吗?

回答by Darin Dimitrov

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.stringifymethod 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). And if you need to support some legacy browsers you could include the json2.jsscript.

这种方法原生内置于所有现代浏览器中(即使 IE8 也支持它,即使 IE8 远非现代浏览器)。如果你需要支持一些旧浏览器,你可以包含json2.js脚本。

回答by rdougan

Create a normal object:

创建一个普通对象:

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

And then use JSON.stringifyto make it a string:

然后使用JSON.stringify使其成为字符串:

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