Hangfish Hangfish - 1 month ago 4
JSON Question

Updating values in a json sting

This is the string I am looking to update.

Koordinatstring =
{
"Koords":"Koordinates",
"TrueCoords":
{
"FirstFind":
{
"X":"134",
"Y":"223",
},
"SecondFind":
{
"X":"721",
"Y":"632",
},
"ThirdFind":
{
"X":"412",
"Y":"344",
},
"FourthFind":
{
"X":"612",
"Y":"532",
}
}
}


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

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'].