您必须解码 JSON 结构并遍历所有字典,直到找到匹配项:
for person in json.loads(user_stream):
if person['name'] == user:
id = person['id']
break
else:
# The else branch is only ever reached if no match was found
raise ValueError('No such person')
如果您需要进行多次查找,您可能希望将此结构转换为 adict
以简化查找:
name_to_id = {p['name']: p['id'] for p in json.loads(user_stream)}
然后直接查找id
:
id = name_to_id.get(name) # if name is not found, id will be None
上面的示例假定名称是唯一的,如果不是,请使用:
from collections import defaultdict
name_to_id = defaultdict(list)
for person in json.loads(user_stream):
name_to_id[person['name']).append(person['id'])
# lookup
ids = name_to_id.get(name, []) # list of ids, defaults to empty
这始终是一种权衡,您以内存换取速度。