【问题标题】:Pasring JSON objects that aren't going to be in every record解析不会出现在每条记录中的 JSON 对象
【发布时间】:2014-04-01 16:20:41
【问题描述】:

我有一些从 Twitter Streaming API 获取的数据,我正在尝试使用 python 进行解析。在解析所有记录中的对象时,我大部分时间都成功地做到了这一点。但是,当尝试解析不在每条记录中的对象时,例如['coordinates']['entities']['hashtags'],我遇到了错误。

import json
import sys

def main():

    for line in sys.stdin:
        line = line.strip()

        data = ''

        try:
            data = json.loads(line)
        except ValueError as detail:
            continue

        if not (isinstance(data, dict)):
            ## not a dictionary, skip
            pass
        elif 'delete' in data:
            ## a delete element, skip for now.
            pass
        elif 'user' not in data:
            ## bizarre userless edge case
            pass
        else:
            print "\t".join([
            data['created_at'],
            data['user']['screen_name'],
            data['user']['id_str'],
            data['user']['lang'],
            data['text'],
            data['source']
            ]).encode('utf-8')

if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python json twitter


    【解决方案1】:

    您可以使用data.get('coordinates'),而不是使用data['coordinates']

    如果键不在字典中,使用dict.get(key) 将返回None,而不是引发KeyError

    【讨论】:

    • 我尝试了data.get('coordinates'),但出现以下错误:TypeError: sequence item 6: expected string or Unicode, NoneType found
    猜你喜欢
    • 2014-05-30
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2018-01-24
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    相关资源
    最近更新 更多