1

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks - actually this is a json file (TXT.json) and i have to write the modified json in there. how do i do that?
2

Convert the JSON object to a Python object, then change the value just like any other Python object.

1 Comment

I guess i am looking for a function that helps me write into a json file (TXT.json) into a specific field like: ['EZMessage']['data']['authToken']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.