I am trying to parse json to find the value of a desired key. I am doing so recursively. If there is another, fast or more efficient way to do so, I am open
example 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
}
}
}
here is what I have so far
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
expected output:
>>> json_scan(json_obj, "timestamp")
1416958459185
As I go through the debugger, I am able to find the the desired value but the line result = None resets result to None and at the end of the method, the value I get is None. I'm not sure how to fix this. I tried removing the line but I get error because result is not preset to a value.
result = json_scan(element, key)result = Noneat all.result = Noneand added the adjustments you suggested for the recursive calls (result = json_scan(json_obj[element], key)andresult = json_scan(element, key))but I am getting the local variable "result" referenced before assignment errorfor element in json_obj:isn't happening in one of the calls (whateverjson_objis is empty), hence you reachreturn resultbefore it gets assigned.