使用 jquery 或 javascript 添加或更改 JSON 键的值

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

Add or change a value of JSON key with jquery or javascript

javascriptjsonjquery

提问by JCam

I have a JSONstring(?)that I have returned from $.ajax()and named it data. Some of the values are empty and I need to add values to some of the keys and send it back to my PHPscript.

我有一个JSONstring(?)我已经返回$.ajax()并命名为data. 有些值是空的,我需要为某些键添加值并将其发送回我的PHP脚本。

I access the existing values by data.keyName. How do I add or change the values of certain keys in "data"?

我通过 data.keyName 访问现有值。如何添加或更改“数据”中某些键的值?

This is what datalooks like.

这就是data它的样子。

{
    "ID":"48",
    "userID":"0",
    "address":"750 North High Street",
    "city":"Columbus",
    "state":"OH",
    "zip":"43215",
    "lat":"39.977673",
    "lng":"-83.003357",
    "busNumber":"55",
    "isClaimed":"N",
    "whereFound":"",
    "busNum":"",
    "email":"",
    "fname":"",
    "lname":"",
    "comments":""
}  

回答by cdhowie

Once you have decoded the JSON, the result is a JavaScript object. Just manipulate it as you would any other object. For example:

解码 JSON 后,结果是一个 JavaScript 对象。就像操作任何其他对象一样操作它。例如:

data.busNum = 12345;
...

回答by sje397

var temp = data.oldKey; // or data['oldKey']
data.newKey = temp;
delete data.oldKey;

回答by epascarello

Just like you would for any other variable, you just set it

就像您对任何其他变量所做的一样,您只需设置它

alert(data.ID);
data.ID = "bar";  //dot notation 
alert(data.ID);    
data.userID = 123456;
data["address"] = "123 some street"; //bracket notation

回答by dongjie

It seems if your key is saved in a variable. data.key = valuewon't work.

看来您的密钥是否保存在变量中。data.key = value不会工作。

You should use data[key] = value

你应该使用 data[key] = value

Example:

例子:

data = {key1:'v1', key2:'v2'};

var mykey = 'key1'; 
data.mykey = 'newv1';
data[mykey] = 'newV2';

console.log(data);

Result:

结果:

{
  "key1": "newV2",
  "key2": "v2",
  "mykey": "newv1"
}

回答by Gajender Singh

var y_axis_name=[];

 for(var point in jsonData[0].data)
              { 
                y_axis_name.push(point);

              }

y_axis_name is having all the key name

y_axis_name 具有所有键名

try on jsfiddle

试试jsfiddle

回答by scheffield

data.userID = "10";