使用python解析JSON:空白字段

Pab*_*rdo 10 python parsing json python-2.7

我在使用python解析JSON时遇到了问题,现在我被卡住了.
问题是我的JSON实体并不总是一样的.JSON是这样的:

"entries":[
{
"summary": "here is the sunnary",
"extensions": {
   "coordinates":"coords",
   "address":"address",
   "name":"name"
   "telephone":"123123"
   "url":"www.blablablah"
},
}
]
Run Code Online (Sandbox Code Playgroud)

我可以通过JSON,例如:

for entrie in entries:
  name =entrie['extensions']['name']
  tel=entrie['extensions']['telephone']
Run Code Online (Sandbox Code Playgroud)

问题来了,因为有时,JSON没有所有"字段",例如,telephone字段,有时会丢失,因此,脚本失败KeyError,因为此条目中缺少关键电话.
所以,我的问题是:我怎么能运行这个脚本,留下一个缺少电话的空白区域?我尝试过:

if entrie['extensions']['telephone']:
    tel=entrie['extensions']['telephone']
Run Code Online (Sandbox Code Playgroud)

但我认为不行.

Ste*_*ppo 15

使用dict.get而不是[]:

entries['extensions'].get('telephone', '')
Run Code Online (Sandbox Code Playgroud)

或者,简单地说:

entries['extensions'].get('telephone')
Run Code Online (Sandbox Code Playgroud)

get将返回第二个参数(默认值None),而不是在KeyError找不到键时引发.


Ray*_*ger 8

如果只有一个地方缺少数据,则可以使用dict.get填写缺少的值:

tel = d['entries'][0]['extensions'].get('telelphone', '')
Run Code Online (Sandbox Code Playgroud)

如果问题更加普遍,您可以让JSON解析器使用defaultdict或自定义词典而不是常规词典.例如,给定JSON字符串:

json_txt = '''{
    "entries": [
        {
            "extensions": {
                "telephone": "123123", 
                "url": "www.blablablah", 
                "name": "name", 
                "coordinates": "coords", 
                "address": "address"
            }, 
            "summary": "here is the summary"
        }
    ]
}'''
Run Code Online (Sandbox Code Playgroud)

解析它:

>>> class BlankDict(dict):
        def __missing__(self, key):
            return ''

>>> d = json.loads(json_txt, object_hook=BlankDict)

>>> d['entries'][0]['summary']
u'here is the summary'

>>> d['entries'][0]['extensions']['color']
''
Run Code Online (Sandbox Code Playgroud)

作为旁注,如果您想清理数据集并强制执行一致性,那么有一个名为Kwalify的优秀工具可以对JSON(和YAML)进行模式验证;