如何将 json 的一部分存储到另一个 json 文件中

How to store a part of json into another json file

我是 json 的新手,我一直在尝试将 json 的一部分存储到另一个文件中,因为我认为这样做比删除不需要的元素更容易。我已经看到 post 如何访问 json 的一部分然后打印它们但不保存它。这是我正在使用的json。

{
  "Id": "Annual report 2019",
  "Date": "25/11/2019",
  "Schools": [
    {
      "Id": "001",
      "Name": "Sunway College",
      "Numbers of teachers": "113",
      "Number of students": "400",
      "Description": null,
      "Partnership": {
        "Schools": [
          "Lancaster University"
        ]
      },
      "Private": true,
      "Annual Revenue": null
    },
    {
      "Id": "002",
      "Name": "Taylors ",
      "Numbers of teachers": "200",
      "Number of students": "600",
      "Description": null,
      "Partnership": {
        "Schools": [
          "CQ University","Thomas More University of Applied Sciences"
        ]
      },
      "Private": true,
      "Annual Revenue": null
    }
  ],
"Created By":"Bobby Williams",
"Date of data collected":"18/8/2019"
}

以及我想将其存储在另一个 json 文件中的内容。

{
  "Schools": [
    {
      "Id": "001",
      "Name": "Sunway College",
      "Numbers of teachers": "113",
      "Number of students": "400",
      "Description": null,
      "Partnership": {
        "Schools": [
          "Lancaster University"
        ]
      },
      "Private": true,
      "Annual Revenue": null
    },
    {
      "Id": "002",
      "Name": "Taylors ",
      "Numbers of teachers": "200",
      "Number of students": "600",
      "Description": null,
      "Partnership": {
        "Schools": [
          "CQ University","Thomas More University of Applied Sciences"
        ]
      },
      "Private": true,
      "Annual Revenue": null
    }
  ]
}

有什么解决方案或post可以帮助我吗?

如果我没有正确理解你的问题,你想将 json 对象的一部分保存到文件中。

如果您想要 json 对象的一部分(即 schools),您可以将其分配为另一个变量并将其存储在文件中。 例如

def get_part_of_json(jsn_obj, key, file_name): 

    new_jsn_obj = jsn_obj[key] 
    new_str = json.dumps(new_jsn_obj)
    file = open(file_name, 'w')
    file.write(new_str)

def read_jsn_string(string_var): 
    return json.loads(string_var)

所以当你写json.dumps时它会把json对象转换成一个字符串。并写 json.loads 你得到相应的 json 对象。

希望对您有所帮助!