0

Let's say I want to parse through 100 json objects and extract a certain element from the object for example "author": "Mark Twain".

If 1 of the 100 json objects is missing information and does not have the "author" key then a key error gets thrown stopping the program.

What's the best way to handle this issue?

Also if there are redundancies in the json object for example there are keys called "authorFirstName": "Mark" and 'authorlastName": "Twain", are there ways to use these instead of the original "author" key, in the case that "author" is missing?

1 Answer 1

3

You can use dict.get('key', default=None) to get the value if the key exists.

Assuming an authors.json file like this:

[
  {
    "author": "Mark Twain"
  },
  {
    "authorFirstName": "Mark",
    "authorLastName": "Twain"
  },
  {
    "noauthor": "error"
  }
]

You can use the following

import json

people = json.load(open("authors.json"))

for person in people:
    author = person.get('author')
    # If there is no author key then author will be None
    if not author:
        # Try to get the first name and last name
        fname, lname = person.get('authorFirstName'), person.get('authorLastName')
        # If both first name and last name keys were present, then combine the data into a single author name
        if fname and lname:
            author = "{} {}".format(fname, lname)

    # Now we either have an author because the author key existed, or we built it from the first and last names.
    if author is not None:
        print("Author is {}".format(author))
    else:
        print("{} does not have an author".format(person))

OUTPUT

Author is Mark Twain
Author is Mark Twain
{u'noauthor': u'error'} does not have an author
Sign up to request clarification or add additional context in comments.

1 Comment

Depending on your requirements, if author is None: may be more appropriate. This will display an error if author is False (well, false in the JSON), "", 0, or 0.00. Or even [] or {} as well. And I think null (which comes out to None in Python, of course).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.