简体   繁体   English

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

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

i have a json variable like this 我有一个像这样的json变量

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

i want to push another key and value to the jsondata. 我想将另一个键和值推送到jsondata。 after that my jsondata have to be like this. 之后我的jsondata必须像这样。

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

how to do that??? 怎么做??? i tried jsondata.push({"FDamount":"false"}) and jsondata.push("FDamount:false"). 我试过jsondata.push({“FDamount”:“false”})和jsondata.push(“FDamount:false”)。 both of these method is not working. 这两种方法都不起作用。

thank you 谢谢

Like this 像这样

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

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 : 顺便说一句,你将boolean定义为string,正确的方法应该是:

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.extend is available when using jQuery (of course), but I'm sure you can find similar methods in other libraries/frameworks. 当使用jQuery(当然)时, jQuery.extend是可用的,但我相信你可以在其他库/框架中找到类似的方法。

(I'm using single quotes, but double quotes works too) (我使用单引号,但双引号也有效)

暂无
暂无

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

相关问题 使用 jQuery 或 JavaScript 添加或更改 JSON 键的值 - Add or change a value of JSON key with jQuery or JavaScript 如何在Javascript / Jquery中使用json中的'Key'获取'Value' - How to get the 'Value' using 'Key' from json in Javascript/Jquery 如何使用javascript在现有的json数组中添加键及其值 - How to add key and its value in existing json array using javascript 如何使用JavaScript将JSON字符串中的键和值添加到innerHTML中 - How to add key and value from JSON string into innerHTML using JavaScript 使用javascript在json文件中添加键和值 - add key and value in json file using javascript 无法使用JavaScript在JSON对象中添加键值 - Unable to add key value in JSON object using javascript 合并具有相同“键”的JSON对象,并使用JavaScript添加其“值” - Merge JSON Object with same “key” and add their “value” using JavaScript 如何使用JavaScript / jquery在不知道键的情况下从多维json数组检索值? - How to retrieve a value from a multidimensional json array without knowing the key using javascript/jquery? 如何使用JavaScript在现有JSON对象中添加新的键值对? - How to add a new key value pair in existing JSON object using JavaScript? 如何迭代 JSON 对象并在 Javascript 中使用其层次结构动态添加键值对对象? - How to Iterate the JSON object and add a key value pair object dynamically using its hierarchy level in Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM