I'm calling many web services in Python which return JSON formatted text describing the same data, but each are structured differently. Rather than write a dozen ways to loop through the data, I'm attempting to create a common base path and common field name, but not understanding now to create a dynamic name to grab the desired field.
service1 calls the street address, "addr1" while service2 calls it, "address1".
service1 JSON path to the street address: ["results"][0]["locations"][0]["addr1"] .
service2 JSON path to the street address: ["query"][0]["address1"] .
service1 response:
{
"results":[
{
"providedLocation":{
"location":"123 Main St. Whoville"
},
"locations":[
{
"addr1":"123 Main St.",
"city":"Whoville"
}
]
}
]
}
From my common terms translation.ini file
[service1]
base_path = '["results"][0]["locations"]'
field = "addr1"
[service2]
base_path = '["query"]'
field = 'address1'
I'm looping through the address locations returned like this:
j = json.loads(response.text)
try:
for i in range(0,count_the_results()):
street_number = j[base_path][i][field] # multiple locations returned
except KeyError:
print("street_number error again")
I tried using eval(), but it drops the brackets ([0]) which breaks the path
j[eval(base_path)]
I tried breaking the base_path into pieces but eval still gets me
base_path = '["results"][0]'
locations = '["locations"]'
j[eval(str(base_path)+str(locations))]
I could use keys, but still have to build the unique path somehow
j.get("results",{})[0].get("locations")[i][field]
Could someone point out what I'm missing in creating the path, please?