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

问题描述 投票:-2回答:1

我是json的新手,我一直试图将json的一部分存储到另一个文件中,因为我认为这样做比删除不需要的元素更容易。我看过有关如何访问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
    }
  ]
}

是否有任何解决方法或帖子可能对我有帮助?

json python-3.7
1个回答
0
投票

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

[如果您想要jsonObject的一部分(即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对象。

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.