23

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":""
}  
2
  • 1
    If you access the values with data.keyName, you no longer have a JSON string. You have a JavaScript object. JSON has already been parsed into an object for you. Commented Dec 13, 2010 at 15:23
  • Thanks for explaining that, Ates. I was confused about that. Commented Dec 13, 2010 at 15:49

8 Answers 8

50

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;
...
Sign up to request clarification or add additional context in comments.

1 Comment

Why didn't I try that... Thanks!
22
var temp = data.oldKey; // or data['oldKey']
data.newKey = temp;
delete data.oldKey;

Comments

8

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"
}

Comments

4

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

Comments

0
data.userID = "10";

1 Comment

If userID exists as a key, this answer duplicates it.
0
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

Comments

0

You just set the data value like a normal javascript variable Ex:

data["userID"] = 4; // or data.userID = 4

Comments

0
//We loop inside the array with "for"
for(let i = 0; i < _arrayJsonItems.length; i++)
{
    //First, we write the keys we want to delete
    delete _arrayJsonItems[i].KeyOne;
    delete _arrayJsonItems[i].KeyTwo;

    //Finally, we add new values ​​with the same key names.
    _arrayJsonItems[i].KeyOne = "NewValue";
    _arrayJsonItems[i].KeyTwo = "NewValue";
    
}

1 Comment

could use forEach: _arrayJsonItems.forEach((item) => { })

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.