I have a JSON
string(?)
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 PHP
script.
I access the existing values by data.keyName. How do I add or change the values of certain keys in "data"?
This is what data
looks like.
{
"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":""
}
This question is related to
javascript
json
jquery
Once you have decoded the JSON, the result is a JavaScript object. Just manipulate it as you would any other object. For example:
data.busNum = 12345;
...
It seems if your key is saved in a variable. data.key = value
won't work.
You should use 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"
}
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
try on jsfiddle
data.userID = "10";
var temp = data.oldKey; // or data['oldKey']
data.newKey = temp;
delete data.oldKey;
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
Source: Stackoverflow.com