I have a best practice question relating to iterating over a JSON file in Python using try/except statements.
I have a JSON file that looks like this (vastly simplified for the question):
"results": [
{
"listingId":"1"
"address":"123 Main st"
"landsize":"190 m2"
},
{
"listingId":"2"
"address":"345 North st"
"state":"California"
}
]
As I stated, this is super simplified, (in my actual problem there are about 30 key value pairs I am interested in, and thousands of records) The challenge is, that even though the keys are pretty consistent (it's always around the same 30), occasionally there will be a missing key/value pair.
If one or two or 10 are missing, I will want the rest of the record to be written out, so my approach at the moment is using a try/catch statement for each key value pair, which seems to strike me as a very inefficient way of checking this, and I am sure there is a better way.
My code looks (kind of) like this (which i am sure is not the best way to do this):
for i in range(len(JSON_data["results"])):
try:
print "ListingID=" + JSON_data["results"][i]["listingId"]
except KeyError:
print "ListingID is unknown"
try:
print "Address=" + JSON_data["results"][i]["address"]
except KeyError:
print "Address is unknown"
try:
print "landsize=" + JSON_data["results"][i]["landsize"]
except KeyError:
print "landsize is unknown"
try:
print "state =" + JSON_data["results"][i]["state"]
except KeyError:
print "state is unknown"
Any advice appreciated!