我正在尝试解析 json 以找到所需键的值。我递归地这样做。如果有另一种更快或更有效的方法,我愿意接受
示例 json:
{
"data_version":"5",
"application":{
"platform":"iPhone",
"os":"iPhone OS",
"locale":"en_US",
"app_version":"unknown",
"mobile":{
"device":"iPhone",
"carrier":"Verizon",
}
},
"event_header":{
"accept_language":"en-us",
"topic_name":"mobile-clickstream",
"server_timestamp":1416958459572,
"version":"1.0"
},
"session":{
"properties":{
}
},
"event":{
"timestamp":1416958459185,
"properties":{
"event_sequence_number":97
}
}
}
这是我目前的情况
def json_scan(json_obj, key):
result = None
for element in json_obj:
if str(element) == key:
result = json_obj[element]
else:
if type(json_obj[element]) == DictType:
json_scan(json_obj[element], key)
elif type(json_obj[element]) == ListType:
json_scan(element, key)
return result
预期输出:
>>> json_scan(json_obj, "timestamp")
1416958459185
当我通过调试器时,我能够找到所需的值,但是 result = None
行将结果重置为 None
并且在方法的末尾,我得到的值是 None
。我不确定如何解决这个问题。我尝试删除该行但出现错误,因为结果未预设为值。
最佳答案
使用 json 库来解析 json 文件(应该删除一些逗号)并使用 native 字典类型:
def json_scan(json_obj, key):
d = json.loads(json_obj)
def _(dictobj, lookup):
if lookup in dictobj.keys():
return dictobj[lookup]
else:
for sub_dictobj in [d for d in dictobj.values() if type(d) == DictType]:
result = _(sub_dictobj, lookup)
if result:
return result
return None
return _(d, key)
更完整的版本:
def json_scan(json_obj, key):
d = json.loads(json_obj)
def _(dictobj, lookup):
if lookup in dictobj.keys():
return dictobj[lookup]
else:
for sub_dictobj in [d for d in dictobj.values() if type(d) == DictType]:
result = _(sub_dictobj, lookup)
if result:
return result
# if objects in dictobj.values() are lists, go through them
for listobject in [l for l in dictobj.values() if type(d) == list]:
for sub_dictobj in [d for d in listobject if type(d) == DictType]:
result = _(sub_dictobj, lookup)
if result:
return result
return None
return _(d, key)
编辑(2015/04/25):
看完 @PyCon 2015 视频后,我遇到了 dict_digger :
http://jtushman.github.io/blog/2013/11/06/dict-digger/ https://github.com/jtushman/dict_digger
它带有测试...
关于python - 解析 JSON 以查找键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27234190/