python修改json⽂件内容,⽤python替换json⽂件中的键我正在做⼀个简单的python脚本来替换json⽂件中的⼀个键,下⾯是我的python脚本
import json
import os
json_dir="/opt/rdm/adggeth/ADGG-ETH-02/20181008/"
json_dir_processed="/opt/rdm/adggeth/ADGG-ETH-02/20181008updated/"
for json_file in os.listdir(json_dir):
if dswith(".json"):
processed_json = "%s%s" % (json_dir_processed, json_file)
json_file = json_dir + json_file
python怎么读取json文件print "Processing %s -> %s" % (json_file, processed_json)
with open(json_file, 'r') as f:
json_data = json.load(f)
if "grp_farmerreg/farmerdetails/farmermobile" not in json_data:
json_data["grp_farmerreg/farmerdetails/farmermobile"] = json_data["grp_farmerdts/hh_id"]
with open(processed_json, 'w') as f:
f.write(json.dumps(json_data, indent=4))
else:
print "%s not a JSON file" % json_file
此脚本提供以下错误:
File "/opt/rdm/adggeth/ADGG-ETH-02/addfidkey.sh", line 16, in
json_data["grp_farmerdts/hh_id"] = json_data["grp_farmerreg/farmerdetails/farmermobile"]
KeyError: 'grp_farmerreg/farmerdetails/farmermobile'
如何成功替换JSON⽂件的密钥
我的⽰例json⽂件如下:为了便于理解,我删除了json⽂件中的⼤部分细节
{
"grp_farmerreg/members_no": "1",
"grp_farmerreg/hh_country": "1",
"_bamboo_dataset_id": "",
"_tags": [],
"grp_farmerreg/totanim": "6",
"gpsloc": "7.0854258 38.6111001 1674.300048828125 17.0",
"grp_farmerreg/farmerdetails/farmermobile": "0913886615",
"grp_farmerreg/grpdetails2/nmale6to14": "1",
"grp_farmerreg/farmerdetails/farmerhhhead": "1",
"grp_farmerreg/grpdetails2/nfem15to64": "0",
"meta/instanceID": "uuid:008aea99-810e-4dbc-9235-4d02b8e8d36b", "_duration": "",
"grp_farmerreg/grpdetails2/nfem6to14": "1",
"grp_farmerreg/grp_e1_ctlca/cattletotalowned": "6",
"start_time": "2018-12-24T11:24:53.034+03",
"_uuid": "008aea99-810e-4dbc-9235-4d02b8e8d36b",
}
我的预期产量
{
"grp_farmerreg/members_no": "1",
"grp_farmerreg/hh_country": "1",
"_bamboo_dataset_id": "",
"_tags": [],
"grp_farmerreg/totanim": "6",
"gpsloc": "7.0854258 38.6111001 1674.300048828125 17.0",
"grp_farmerreg/farmerdetails/farmermobile": "0913886615",
"grp_farmerdts/hh_id":"0913886615",
"grp_farmerreg/grpdetails2/nmale6to14": "1",
"grp_farmerreg/farmerdetails/farmerhhhead": "1",
"grp_farmerreg/grpdetails2/nfem15to64": "0",
"meta/instanceID": "uuid:008aea99-810e-4dbc-9235-4d02b8e8d36b", "_duration": "",
"grp_farmerreg/grpdetails2/nfem6to14": "1",
"grp_farmerreg/grp_e1_ctlca/cattletotalowned": "6",
"start_time": "2018-12-24T11:24:53.034+03",
"_uuid": "008aea99-810e-4dbc-9235-4d02b8e8d36b",
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论