如何使用python重命名json key?

kninwzqo  于 2023-01-14  发布在  Python
关注(0)|答案(1)|浏览(198)

我有json文件,我需要使用python将folder_path键重命名为backup_folder_path

{
  "urn:adsk.wipprod:dm.lineage:smth": {
    "bim_manifest_urn": "urn:foo/bar/z",
    "gs_id": "foobar",
    "versions": {
      "1": "1"
    },
    "folder_path": "/foo/bar"
  },
  "urn:adsk.wipprod:dm.lineage:smth": {
    "bim_manifest_urn": "urn:foo/bar",
    "gs_id": "foobar1",
    "versions": {
      "1": "1"
    },
    "folder_path": "/foo/barС"
  },

我想做的是:

def edit_string_name():
    with open(r"smth.json", encoding="utf-8") as json_data:
        data = json.load(json_data)
        
        data = {'folder_path'}
        data['backup_folder_path'] = data.pop('folder_path')
        print(data)
    
if __name__ == '__main__':
    edit_string_name()

但似乎什么也没发生。当我试图循环通过时,我在终端中得到了废话。

yzuktlbb

yzuktlbb1#

这个应该可以了

def edit_string_name():
  with open("smth.json", "r+", encoding="utf-8") as file:
    data    = json.load(file)
    content = data["urn:adsk.wipprod:dm.lineage:smth"]

    content["backup_folder_path"] = content["folder_path"]
    content.pop("folder_path")
    data["urn:adsk.wipprod:dm.lineage:smth"] = content

    # Updating the file
    file.seek(0)
    file.write(json.dumps(data, indent=4))
    file.truncate()

edit_string_name()

相关问题