json - 解析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)
两者都提供几乎相同的性能。我怎样才能非常有效和更快地解析这个。请帮忙。
解决方案
推荐阅读
- spring-boot - Mybatis XML - 在 keyColumn 属性中指定表名
- python - Python,Django:如何将检查的表行放入列表中?
- javascript - MongoDB 聚合 vs 使用 javascript 函数性能
- flutter - 使用 Flutter 和 Ferry 获取数据后无法使用来自 GraphQl 查询的数据
- reactjs - 为什么 useEffect 挂钩看不到我的对象?
- php - 循环遍历具有大量行数的 postgres 查询结果是否存在危险?
- python-3.x - 加入时如何强制绝对路径是相对的?
- reactjs - error_message: '请求的产品还没有准备好。请提供一个 webhook 或稍后再试一次请求',
- javascript - 类型错误:无法读取未定义的属性“值”(第 2 行,文件“自动填充 Google 文档”)
- c# - 为什么用 SharpGL 绘制的所有立方体都是白色的?