Python,解析JSON对象时正确处理Key Errors
Python, properly handle Key Errors when parsing JSON object
假设我想解析 100 个 json 对象并从对象中提取某个元素,例如 "author":"Mark Twain".
如果 100 个 json 对象中有 1 个缺少信息并且没有 "author" 键,则会引发键错误并停止程序。
处理此问题的最佳方法是什么?
此外,如果 json 对象中存在冗余,例如有名为 "authorFirstName" 的键:"Mark" 和 'authorlastName":"Twain",
在 "author" 丢失的情况下,有没有办法使用这些而不是原来的 "author" 键?
如果键存在,您可以使用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
假设我想解析 100 个 json 对象并从对象中提取某个元素,例如 "author":"Mark Twain".
如果 100 个 json 对象中有 1 个缺少信息并且没有 "author" 键,则会引发键错误并停止程序。
处理此问题的最佳方法是什么?
此外,如果 json 对象中存在冗余,例如有名为 "authorFirstName" 的键:"Mark" 和 'authorlastName":"Twain", 在 "author" 丢失的情况下,有没有办法使用这些而不是原来的 "author" 键?
如果键存在,您可以使用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