Home > Software design >  Parsing JSON with Python - Case Sensitivity for Keys
Parsing JSON with Python - Case Sensitivity for Keys

Time:04-04

I'm trying to read a json from mulitple REST end points using json.load - the key I'm interested in however has a different case depending on which end point (some are 'name' others are 'Name'). I've tried the following to get around it:

for x in urls:
    response_json = json.load(urllib.request.urlopen(x))
    try:
        projects.append(response_json['attributes']['Name'])
        print(response_json['attributes']['Name'])
    except:
        projects.append(response_json['attributes']['name'])
        print(response_json['attributes']['name'])

However I'm getting KeyErrors for both permutations of the 'name' key. The code works fine if I remove the TRY...EXCEPT and only specify one case but then I need to know what is it for each URL. Why would that be? is there a better approach?

CodePudding user response:

You should only use try and catch for error handling.

Instead of using try and catch to split your code, you can use a simple if-else condition check. It'll allow you to check for more conditions. Keep in mind that the below might not be the exact code since I don't have your JSON, however, this should guide you towards the solution here.

if 'Name' in response_json['attributes']:
    print(response_json['attributes']['Name'])
elif 'name' in response_json['attributes']:
    print(response_json['attributes']['name'])
else:
    print(response_json['attributes'].keys())
  • Related