Python,在解析JSON对象时正确处理键错误

时间:2016-05-02 21:52:11

标签: python json parsing error-handling key

假设我要解析100个json对象并从对象中提取某个元素,例如“author”:“Mark Twain”。

如果100个json对象中有1个缺少信息且没有“author”键,则会抛出一个键错误来停止该程序。

处理此问题的最佳方法是什么?

此外,如果json对象中存在冗余,例如存在名为“authorFirstName”的键:“Mark”和“authorlastName”:“Twain”, 在“作者”缺失的情况下,有没有办法使用这些而不是原始的“作者”键?

1 个答案:

答案 0 :(得分:3)

如果密钥存在,您可以使用dict.get('key', default=None)获取值。

假设authors.json文件是这样的:

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

您可以使用以下

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))

<强>输出

Author is Mark Twain
Author is Mark Twain
{u'noauthor': u'error'} does not have an author