繁体   English   中英

如何使用 python 将修改后的数据添加到我的 json 文件的顶部?

[英]How do I add modified data to the top of my json file using python?

我有一个需要修改的 json 文件。 我已经成功地做到了,但是当我将它推送到 json 文件时,它会出现在底部,就像附加了一样。 我正在使用 seek(0) 但这似乎不起作用。 有什么建议么?

f = open("C:\last_esri.json", "r")
data = json.load(f)
f.close()

for i in(data['fields']):
    for item in i:
        if i[item] == 'esriFieldTypeOID':
            i.update({'type' :'oid'})
        elif i[item] == 'esriFieldTypeString':
            i.update({'type' :'string'})
        elif i[item] == 'esriFieldTypeInteger':
            i.update({'type' :'integer'})
        elif i[item] == 'esriFieldTypeDouble':
            i.update({'type' :'double'})
        elif i[item] == 'esriFieldTypeDate':
            i.update({'type' :'date'})
 

f = open("C:\data\last_esri.json", 'w+')
f.seek(0)
f.write(json.dumps(data, indent=1))
f.close()         

这不是字典的想法。 它没有顺序 如果您确实希望它按特定顺序排列,则应使用列表。

编辑:即使它不实用,如果你真的希望它位于顶部,你可以更新你的新字典,如图所示:

def update_on_top(old:dict, new:dict) -> dict:
  new.update(old)
  return new


x = {"a":3, "b":4, "c":8, "z":9}
y = {"e":2}

updated = update_on_top(x, y)

print(updated)

这会将“新”字典放在“旧”字典之前。 此示例的输出:

{'e': 2, 'a': 3, 'b': 4, 'c': 8, 'z': 9}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM