首页 > 解决方案 > 使用python修改json文件

问题描述

嗨,我有一个像这样的 json 文件。

{
 a : {
       b:"b_value",
       c:"c_value"
     }
}

我想读取json文件并使用python进行修改,所以文件内容将是这样的

{
 a : {
       x:{
          b:"b_value",
          c:"c_value"
         }

     }
}

请大家帮忙谢谢。

标签: pythonjson

解决方案


  1. 将json读入字典:
import json
with open("json_file.json", "r") as f:
    data = json.load(f)
  1. 使用创建您想要的结构data
manipulated_data = {"a" : { "x": data["a"] } }
  1. 将您的文件写入manipulated_data文件:
with open("json_file.json", "w") as f:
    json.dump(f, manipulated_data)

推荐阅读