首页 > 解决方案 > 解析json python的高效最快方法

问题描述

我在文件中有一个 JSON 内容,我需要迭代 JSON 以仅获取特定的键及其值。(值是另一个字典)

{"100": {"aaa": {"Data": [10387], "Index": 90}, 
         "bbb": {"Data": [10387], "Index": 90}, 
         "ccc": {"Data": [10387], "Index": 90}, 
         "ddd": {"Data": [10387], "Index": 90}
         ....
        },
"200": {"aaa": {"Data": [10387], "Index": 90}, 
        "bbb": {"Data": [10387], "Index": 90}, 
        "ccc": {"Data": [10387], "Index": 90}, 
        "ddd": {"Data": [10387], "Index": 90}
        ....
        },
   ....
   }

我对脚本的输入如下。ID 和名称列表。例如 1. Ids =>[100,200] , name => ["aaa","bbb"] 或 Ids => [100], ["aaa","bbb","ccc"] ....

我需要解析 JSON 内容并仅从内容中获取 ID 和名称并创建另一个 JSON。我的代码如下:

def read_json_file(self, json_filename):
        file_path = os.path.join(self.mock_file_dir, json_filename)
        with open(file_path) as file:
            content = file.read()
        return content

我的第一种方法(dict理解)。输入 ID=[100,200] ,名称:['aaa','bbb']

  content = json.loads(read_json_file(json_filename))
  ids_in_json = content.keys()

  result = {id: {name: content[str(id)][name]
                   for name in names} for id in Ids
                   if str(id ) in ids_in_json }

  return json.dumps(result)

第二种方法(For循环)

result = {}
  content = json.loads(read_json_file(json_pm_filename))
  ids_in_json = content.keys()

  for id in Ids:
    if str(id) in content.keys():
       for name in names:
          result[cell].update({name : content[str(id)][name]})

  return json.dumps(result)

两者都提供几乎相同的性能。我怎样才能非常有效和更快地解析这个。请帮忙。

标签: jsonpython-3.x

解决方案


推荐阅读