如何使用 javascript 或 jquery 向 json 添加键和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14002300/
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 15:23:38  来源:igfitidea点击:

how to add key and a value to a json using javascript or jquery

javascriptjson

提问by JSAddict

i have a json variable like this

我有一个像这样的 json 变量

var jsondata={"all":"true"}

i want to push another key and value to the jsondata. after that my jsondata have to be like this.

我想将另一个键和值推送到 jsondata。之后我的jsondata必须是这样的。

{"all":"true","FDamount":"false","DDamount":"true"}

how to do that??? i tried jsondata.push({"FDamount":"false"}) and jsondata.push("FDamount:false"). both of these method is not working.

怎么做???我试过 jsondata.push({"FDamount":"false"}) 和 jsondata.push("FDamount:false")。这两种方法都行不通。

thank you

谢谢你

回答by senK

Like this

像这样

jsondata.FDamount = 'false';
// or
jsondata['FDamount'] = 'false';

回答by Cyril N.

Simply do this :

只需这样做:

jsondata['FDamount'] = 'false';
jsondata['DDamount'] = 'true';

Or this :

或这个 :

jsondata.FDamount = 'false';
jsondata.DDamount = 'true';

By the way, you define boolean as string, the correct way should be :

顺便说一句,您将布尔值定义为字符串,正确的方法应该是:

jsondata['FDamount'] = false;
jsondata['DDamount'] = true;

To push a little bit further, you can use jQuery.extend to extend the original var, like this :

为了更进一步,您可以使用 jQuery.extend 扩展原始 var,如下所示:

jQuery.extend(jsondata, {'FDamount': 'false', 'DDamount': 'true'});
// Now, jsondata will be :
{"all":"true","FDamount":"false","DDamount":"true"}

jQuery.extendis available when using jQuery (of course), but I'm sure you can find similar methods in other libraries/frameworks.

jQuery.extend在使用 jQuery 时可用(当然),但我相信你可以在其他库/框架中找到类似的方法。

(I'm using single quotes, but double quotes works too)

(我使用单引号,但双引号也适用)