解析 json 而不明确调用键名

parse json without explciitely calling the key-name

我有一个类似 json 的文件,每行有效 json,看起来像

{"Some_key": {"name": "Tom", "school_code":"5678", "sport": "football", "score":"3.46", "classId": "456"}}
{"Another_one": {"name": "Helen", "school_code":"7657", "sport": ["swimming", "score":"9.8", "classId": "865"}}
{"Yet_another_one_": {"name": "Mikle", "school_code":"7655", "sport": "tennis", "score":"5.7", "classId": "76532"}}

所以我需要通过提取这些第一个键(即 "Some_Key" , "Another_key" 等),我事先不知道,然后将字典中 score 键的值与它们相关联。所以像:

("Some_key":"3.46", "Another_Key":"9.8", "Yet_another_one_"; "5.7")

我不知道在不显式调用键名的情况下提取内容的方法,所以非常欢迎您的想法!

这适用于 Python2 和 Python3

>>> {k: v.get('score') for item in data for k, v in item.items()}
{'Another_one': '9.8', 'Some_key': '3.46', 'Yet_another_one_': '5.7'}

如果 json-like 文件确实在每一行都有有效的 json(你的例子不完全),你可以做类似下面的事情(在 Python 2或 3):

import json

with open('json-like.txt') as data_file:
    objs = (json.loads(line).popitem() for line in data_file)
    data = {key: value['score'] for key, value in objs}

print(data) # -> {'Yet_another_one_': '5.7', 'Another_one': '9.8', 'Some_key': '3.46'}