为了账号安全,请及时绑定邮箱和手机立即绑定

如何更改 JSON 文件中的嵌套值?

如何更改 JSON 文件中的嵌套值?

芜湖不芜 2023-03-01 15:57:48
如果“ID”匹配,我试图更改特定的嵌套值(“pH”),但它只更改第一个而不是我想要的那个。我想做什么:{    "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": [                    [                    ]                ]            }        }    ]}但它改变了“ID”为 1 的“pH 值”和“ID”:2 的“pH”值保持不变。这是我的代码:import jsonwith 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 回答

?
胡说叔叔

TA贡献1804条经验 获得超8个赞

您需要在遍历时进行枚举data['features'],以便可以分配回正确的值

data['features'][0]仅分配给ph列表索引 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()


查看完整回答
反对 回复 2023-03-01
?
慕工程0101907

TA贡献1887条经验 获得超5个赞

data['features'][0]

由 [0] 索引,因此修改data["features"]. 您希望它根据评估为True您的条件的索引进行修改feature['properties']["ID"] == 2。


尝试


for index, feature in enumerate(data['features']):

    ...

    if feature['properties']["ID"] == 2:

        data['features'][index]['properties']["pH"] = 10

    ...


查看完整回答
反对 回复 2023-03-01
  • 2 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信