Python,在解析JSON对象时正确处理键错误
假设我想解析100个json对象,并从对象中提取某个元素,例如“author”:“Mark Twain” 如果100个json对象中有1个缺少信息并且没有“author”键,则会在停止程序时抛出一个键错误 处理这个问题的最佳方式是什么 此外,如果json对象中存在冗余,例如,存在名为“authorFirstName”:“Mark”和“authorlastName”:“Twain”的键, 在缺少“author”的情况下,是否有方法使用这些键而不是原始的“author”键?如果键存在,可以使用Python,在解析JSON对象时正确处理键错误,python,json,parsing,error-handling,key,Python,Json,Parsing,Error Handling,Key,假设我想解析100个json对象,并从对象中提取某个元素,例如“author”:“Mark Twain” 如果100个json对象中有1个缺少信息并且没有“author”键,则会在停止程序时抛出一个键错误 处理这个问题的最佳方式是什么 此外,如果json对象中存在冗余,例如,存在名为“authorFirstName”:“Mark”和“authorlastName”:“Twain”的键, 在缺少“author”的情况下,是否有方法使用这些键而不是原始的“author”键?如果键存在,可以使用dic
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
如果键存在,可以使用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
根据您的要求,
如果author为None:
可能更合适。如果author
为False
(在JSON中为False
)、、0
或0.00
,甚至[]
或{code>
也会显示错误。我认为为null
(当然,在Python中是None
)。根据您的要求,如果author是None:
可能更合适。如果author
是False
(在JSON中是False
)、”、0
、或0.00
,甚至[]
或{}
也是。我认为null
(当然,在Python中,None
)。