Hangfish Hangfish - 1 year ago 74
JSON Question

Updating values in a json sting

This is the string I am looking to update.

Koordinatstring =

I know how to extract only the X or Y value from FourthFind for example. But what I am looking to do at the moment, is to access that value and replace it with a new one that I want to input.

I would like to do something simliar to:

k = json.dumps(koordinatstring)
l = json.loads(k)

Kords1 = l['TrueCoords']['FirstFind']['X']

To overwrite data, but I don't know if that is possible.

Answer Source

Even though the data may have come from a JSON document, once parsed you have ordinary dictionaries referencing other ordinary dictionaries.

You can always assign to a key in a dictionary:

 d = {'foo': 'bar'}
 d['foo'] = 'spam'

You just have a nested dictionary, so you need to string together a few [...] subscriptions to access the one you want to change:

l['TrueCoords']['FourthFind']['X'] = '42'

This sets the 'X' key to the new value '42', in the dictionary referenced by l['TrueCoords']['FourthFind'].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download