当元素不存在时处理 JSON Parsing TypeError 的正确方法 [英] Proper way of handling JSON Parsing TypeError when element does not exist
问题描述
代码最终得到了我想要的.(这是从一个非常大的json数据集中创建一个我想要的字段的字典列表,以便我可以创建一个数据框来进行额外的数据处理)
The code get's me what I want in the end. (which is to create a list of dictionary of the fields I want from a very large json dataset, so that I can create a dataframe for additional data processing)
但是,我必须构建一个非常大的 try/expect 块才能完成此操作.我想知道是否有更清晰/更聪明的方法来做到这一点.
However I have to construct a very large try/expect block to get this done. I am was wondering if there is a clearer/clever way of doing this.
我遇到的问题是 details['element'] 有时不存在或有值,如果它在子元素上不存在,则会抛出 NoneType 异常['Value'] 无法抓取,因为它不存在.
The problem I'm having is that the details['element'] sometimes don't exist or have a value, which throws a NoneType exception if it does not exist on the child element['Value'] cannot be grabbed because it does not exist.
因此,如果发生这种情况,我有一个非常大的 try/except 块来将变量设置为 ''.
So I have a very large try/except block to set the variable to '' if that happens.
我尝试将 details['element'] 发送到一个函数,该函数将向变量输出返回值...但看起来我不能这样做,因为 Python 会检查元素是否为 NoneType 在将它传递给函数之前发生,这发生在将它发送到函数之前.
I tried to send the details['element'] to a function that would output a return value to the variable...but it looks like I can't do that, because Python checks if the element is a NoneType before passing it through the function, and this happens before sending it to the function.
有什么想法吗?
rawJson = json.loads(data.decode('utf-8'))
issues = rawJson['issues']
print('Parsing data...')
for ticket in issues:
details = ticket['fields']
try:
key = ticket['key']
except TypeError:
key = ''
try:
issueType = details['issuetype']['name']
except TypeError:
issueType = ''
try:
description = details['description']
except TypeError:
description = ''
try:
status = details['status']['name']
except TypeError:
status = ''
try:
creator = details['creator']['displayName']
except TypeError:
creator =''
try:
assignee = details['assignee']['displayName']
except TypeError:
assignee =''
try:
lob = details['customfield_10060']['value']
except TypeError:
lob =''
.... There is a long list of this
推荐答案
您可以使用 get
方法 允许提供默认值以简化此代码:
You can use get
method which allows to provide a default value to simplify this code:
d = {'a': 1, 'c': 2}
value = d.get('a', 0) // value = 1 here because d['a'] exists
value = d.get('b', 0) // value = 0 here because d['b'] does not exist
所以你可以写:
for ticket in issues:
details = ticket['fields']
key = ticket.get('key', '')
description = details.get('description', '')
issueType = details['issuetype'].get('name') if 'issuetype' in details else ''
...
这篇关于当元素不存在时处理 JSON Parsing TypeError 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!