Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add or change a value of JSON key with jQuery or JavaScript

Tags:

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":"" }   
like image 297
JCam Avatar asked Dec 13 '10 15:12

JCam


2 Answers

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; ... 
like image 173
cdhowie Avatar answered Nov 27 '22 14:11

cdhowie


var temp = data.oldKey; // or data['oldKey'] data.newKey = temp; delete data.oldKey; 
like image 45
sje397 Avatar answered Nov 27 '22 14:11

sje397