Reputation: 23
how do i edit/change a particular field in a json file using python code:
{
"EZMessage":{
"action":"account.cash",
"data":{
"authToken":"123456",
"account":"#ACCOUNTID#",
"portfolio":"true",
"historical":"true"
}
}
}
in this json code, i want to replace 123456 with 789123
string replace only works if i know what is written there. in my code, i would only know what to write, and the identifier "authToken". Is there a way to overwrite the 123456 by identifying that it is the value of "authToken" ?
thanks,
RS
Upvotes: 1
Views: 3963
Reputation: 87376
Use the json module to convert the string to a set of nested dict
objects, make your changes, and then dump the dictionary back to a json string.
import json
jstr = '''{
"EZMessage":{
"action":"account.cash",
"data":{
"authToken":"123456",
"account":"#ACCOUNTID#",
"portfolio":"true",
"historical":"true"
}
}
}'''
j = json.loads(jstr)
j['EZMessage']['data']['authToken'] = 654321
jstr = json.dumps(j)
For how to read-from/write-to a file see the fine tutorial.
Upvotes: 3
Reputation: 1071
Convert the JSON object to a Python object, then change the value just like any other Python object.
Upvotes: 2