def query_json(json_content, query, delimiter='.'):
raise_flag = False
try:
for key in query.split(delimiter):
if isinstance(json_content, list):
json_content = json_content[int(key)]
elif isinstance(json_content, dict):
json_content = json_content[key]
else:
raise_flag = True
except (KeyError, ValueError, IndexError):
raise_flag = True
if raise_flag:
err_msg = u"Failed to extract! => {}\n".format(query)
raise Exception(err_msg)
return json_content
使用:
if __name__ == '__main__':
li1 = {"type": "vcg","id": {"11":1}}
li2 = [{"type": "vcg","id": "VCG111304748293"},{"type": "vcg","id": "VCG111304748293"}]
print(query_json(li1,'id.11'))
print(query_json(li2,'0.type'))
输出:
1
vcg
网友评论