How do I change nested value in JSON file?

Viewed 50

I am trying to change a specific nested value ("pH") if the "ID" matches , but it only changes the first one and not the one I intended.

What I am trying to do:

{
    "type": "FeatureCollection",
    "name": "test",
    "crs": {
        "type": "name",
        "properties": {
            "name": "urn:ogc:def:crs:EPSG::3059"
        }
    },
    "features": [{
            "type": "Feature",
            "properties": {
                "ID": 1,
                "pH": 3.5,
                "P": 2.8,
                "K": 11.0,
                "Mg": 15.8
            },
            "geometry": {
                "type": "Polygon",
                "coordinates": [
                    [

                    ]
                ]
            }
        }, {
            "type": "Feature",
            "properties": {
                "ID": 2,
                "pH": 3,
                "P": 2.5,
                "K": 11.1,
                "Mg": 15.8
            },
            "geometry": {
                "type": "Polygon",
                "coordinates": [
                    [

                    ]
                ]
            }
        }
    ]
}

But it changes the "pH value where "ID" is 1 and "pH" value where "ID": 2 stays the same.

Here is my code:

import json

with open('filepath', 'r+') as f:
    data = json.load(f)

    for feature in data['features']:

        print(feature['properties'])
        if feature['properties']["ID"] == 2:

            data['features'][0]['properties']["pH"]=10
            f.seek(0)
            json.dump(data, f, indent=4)
            f.truncate()
2 Answers
  • You need to enumerate while you iterate through data['features'] so you can assign back to the correct value
    • data['features'][0] assigns only to ph in list index 0.
with open('filepath', 'r+') as f:
    data = json.load(f)

    for i, feature in enumerate(data['features']):  # enumerate while iterating

        print(feature['properties'])
        if feature['properties']["ID"] == 2:

            data['features'][i]['properties']["pH"]=10  # assign back to the correct index location
            f.seek(0)
            json.dump(data, f)
            f.truncate()
data['features'][0]

is indexing by [0] and therefore modifying the first "feature" in data["features"]. You want it to modify based on the index that evaluates to True on your condition feature['properties']["ID"] == 2.

Try

for index, feature in enumerate(data['features']):
    ...
    if feature['properties']["ID"] == 2:
        data['features'][index]['properties']["pH"] = 10
    ...
Related