亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何更改 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 關注
  • 189 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號