【问题标题】:Python, properly handle Key Errors when parsing JSON objectPython,在解析 JSON 对象时正确处理关键错误
【发布时间】:2016-05-02 21:52:11
【问题描述】:

假设我想解析 100 个 json 对象并从对象中提取某个元素,例如“作者”:“马克吐温”。

如果 100 个 json 对象中有 1 个缺少信息并且没有“作者”键,则会引发键错误以停止程序。

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

此外,如果 json 对象中存在冗余,例如有名为“authorFirstName”的键:“Mark”和“authorlastName”:“Twain”, 如果“作者”丢失,有没有办法使用这些来代替原来的“作者”键?

【问题讨论】:

    标签: python json parsing error-handling key


    【解决方案1】:

    如果键存在,您可以使用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
    

    【讨论】:

    • 根据您的要求,if author is None: 可能更合适。如果authorFalse(在JSON 中是false)、""00.00,这将显示错误。甚至[]{} 也是如此。我认为null(当然,在 Python 中是 None)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 2014-09-17
    • 2019-06-28
    相关资源
    最近更新 更多