copying data from json response [Python]
I have a scenario where I am trying to extract data from json response which is obtained from the GET request and then rebuilding the json data by changing some values and then sending a PUT request at same time after rebuilding the json data(i.e, after changing idter
value) below is the target json response.
target_json = { "name": "toggapp", "ts": [ 1234, 3456 ], "gs": [ { "id": 4491, "con": "mno" }, { "id": 4494, "con": "hkl" } ], "idter": 500, "datapart": false }
from the above json I am trying to change the idter
value to my custom value and rebuild it into json data again and post the new json data. Here is what I have tried :
headers = {'Authorization': 'bearer ' + auth_token, 'Content-Type':'application/json', 'Accept':'application/json'} tesstid =[7865, 7536, 7789] requiredbdy = [] for key in testid: get_metadata_targetjson= requests.get('https://myapp.com/%s' %key, headers = headers) metadata=get_metadata_target.json() for key1 in metadata: requiredbdy.append( { "metadata" : [{ "name": key1['name'], "ts": key1['ts'], "gs": key1[gs], "idter": 100, #custom value which I want to change "datapart": false } ] } ) send_metadata_newjson= requests.put('https://myapp.com/%s' %key, headers = headers data = requiredbdy) print(send_metadata_newjson.status_code)
Is this approach fine or How do I proceed in order to achieve this scenario.
You can use the built-in json
module for this like so
import json my_json = """ { "name": "toggapp", "ts": [ 1234, 3456 ], "gs": [ { "id": 4491, "con": "mno" }, { "id": 4494, "con": "hkl" } ], "idter": 500, "datapart": false } """ json_obj = json.loads(my_json) json_obj['idter'] = 600 print(json.dumps(json_obj))
Prints
{"name": "toggapp", "ts": [1234, 3456], "gs": [{"id": 4491, "con": "mno"}, {"id": 4494, "con": "hkl"}], "idter": 600, "datapart": false}
There’s this small script used it to find entries in some very long and unnerving JSONs. not very beautifull und badly documented but maybe helps in your scenario.
from RecursiveSearch import Retriever def alter_data(json_data, key, original, newval): ''' Alter *all* values of said keys ''' retr = Retriever(json_data) for item_no, item in enumerate(retr.__track__(key)): # i.e. all 'value' # Pick parent objects with a last element False in the __track__() result, # indicating that `key` is either a dict key or a set element if not item[-1]: parent = retr.get_parent(key, item_no) try: if parent[key] == original: parent[key] = newval except TypeError: # It's a set, this is not the key you're looking for pass if __name__ == '__main__': alter_data(notification, key='value', original = '********** THIS SHOULD BE UPDATED **********', newval = '*UPDATED*')