簡體   English   中英

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

[英]How do I change nested value in JSON file?

如果“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 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()
  • 您需要在遍歷data['features']時進行枚舉,以便您可以分配回正確的值
    • data['features'][0]僅分配給列表索引 0 中的ph
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]

正在按 [0] 進行索引,因此修改了data["features"]中的第一個“特征”。 您希望它根據在您的條件feature['properties']["ID"] == 2上評估為True的索引進行修改。

嘗試

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM