【问题标题】:Extract part of json file using Python in another json file在另一个 json 文件中使用 Python 提取部分 json 文件
【发布时间】:2020-07-08 22:24:14
【问题描述】:

我想根据键列表提取现有 JSON 文件的一部分并将其保存到另一个 JSON 文件中 例如-

{
"211": {
        "year": "2020",
        "field": "chemistry"
    },
"51": {
        "year": "2019",
        "field":"physics"
},
"5": {
        "year": "2014",
        "field":"Literature"
}

假设列表 =[5,51]

输出的 json 文件应该包含

 {
    "5": {
            "year": "2014",
            "field":"Literature"
         },
    "51": {
            "year": "2019",
            "field":"physics"
           }
    }

} 它不应包含密钥 211 的数据

【问题讨论】:

  • 有10k+行。以上只是一个例子

标签: json python-3.x list


【解决方案1】:

我相信这对你有用:

import json

# Open input file and deserialize JSON to a dict
with open("input_file.json", "r", encoding="utf8") as read_file:
     input_file_dict = json.load(read_file)

# List of id's you want
inc_id_list = [5,51,2,101]

output_dict = dict()

# Iterate over the input file JSON and only add the items in the list
for id in input_file_dict.keys():
    if int(id) in inc_id_list:
        output_dict[id] = input_file_dict.get(id)

# Serialize output dict to JSON and write to output file 
with open('output_file.json', 'w') as output_json_file:
  json.dump(output_dict, output_json_file)

【讨论】:

  • 这不能使用,因为没有特定的开始和结束 id。上面是一个例子。我有大约 10k+ 行不同的 id
  • 如果你的意思是它是一个任意的 id 列表,而不是一个范围,那么所要做的就是将 if 语句更改为“if int(id) in list” 我只是更新我的代码。
【解决方案2】:

试试这个:

l=  {
    "211": {
            "year": "2020",
            "field": "chemistry"
        },
    "51": {
            "year": "2019",
            "field":"physics"
    },
    "5": {
            "year": "2014",
            "field":"Literature"
    } }

    for i,v in l.items():
       if(i!="211"):
           print(i,v)

【讨论】:

  • 谢谢你的解决方案。但是有10k+行。上面只是一个例子。我很难生成一个不需要的密钥列表。你能建议任何其他解决方案
  • 我们可以将不需要的键列表放入另一个列表中并说类似不在列表 l 中的内容吗?
【解决方案3】:

它是一个 JSON 字典,末尾缺少一个括号,因此很容易理解:

mydict = { "211": { "year": "2020", "field": "chemistry" }, "51": { "year": "2019", "field":"physics" }, "5": { "year": "2014", "field":"Literature" }}

incList = [5, 51]

myAnswer = {k:v for (k,v) in mydict.items() if int(k) in incList}

【讨论】:

    猜你喜欢
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 2022-01-03
    相关资源
    最近更新 更多