首页 > 解决方案 > 在多个 JSON 文件中查找包含特定键值的 JSON 文件

问题描述

所以,我有 5 个 JSON 文件,分别命名为 JSON1、JSON2、JSON3、JSON4 和 JSON5。这些 json 文件的一般格式是

JSON文件的一般格式

{
  "flower": {
    "price": {
      "type": "good",
      "value": 5282.0,
      "direction": "up"
     }
    },
  "furniture": {
    "price": {
      "type": "comfy",
      "value": 9074.0,
      "direction": "down"
     }
   }
}

在所有这些 json 文件中,我需要找到具有用户给出的特定值/数据的 json 文件。例如,如果用户为“值”= 9074提供输入,它希望在所有 JSON 文件中搜索,并提供作为 JSON 文件的输出,其中包含提到的值以及具有提到的数据的行。

我使用的方法是:

import json
with open('JSON1.json','r') as f1:
    item1 = json.load(f1)
with open('JSON2.json','r') as f1:
    item2 = json.load(f1)
with open('JSON3.json','r') as f1:
    item3 = json.load(f1)
with open('JSON4.json','r') as f1:
    item4 = json.load(f1)
with open('JSON5.json','r') as f1:
    item5 = json.load(f1)
# Input the value that user want to search
item = input("Enter the value:\n")

# function to search the json file
def search_json(value):
 int i = 0;
  for keyvalue in item(i+1):
    i++;
    if value == keyval['value']
      return keyvalue[name of the json file]

if(search_json(item) !=None):
 print("this value is present in json log :",search_json(item))

观察到的输出应该是:

输入值:9074

此值存在于 json 日志JSON1中,并且存在于12行代码中

但是,上述方法既不高效也不正确。因为,我是学习 python 的新手,因此我对正确的方法感到困惑。如果有人可以提供帮助,将不胜感激。

标签: pythonjsonpandascmd

解决方案


循环遍历文件名。

def find_value_in_json_files(value, files):
    for f in files:
        with open(f) as f:
            item = json.load(f)
        for k, v in item.items():
            price = v['price']
            if price.get('value', price.get('values') == value:
                return f, k

print(find_value_in_json_files(9074, ['JSON1.json', 'JSON2.json', 'JSON3.json', 'JSON4.json', 'JSON5.json']))

推荐阅读