JSON 文件选择键和值出错



我的json文件看起来像这样:

{'id_str': '1179123803420598275',
'quote_count': 0,
'lang': 'hi',
'in_reply_to_status_id': None,
'geo': None,
'user': {'id_str': '832041700394749952',
'verified': False,
'id': 832041700394749952,
'translator_type': 'none',
'profile_sidebar_fill_color': 'DDEEF6',
'contributors_enabled': False,
'url': None,
'location': 'karnavati City, India',
'name': 'Hemraj Padhiyar',
'profile_background_image_url_https': '',
'protected': False,
'screen_name': 'hemrajpadhiyar',
'profile_use_background_image': True,
'profile_text_color': '333333',
'default_profile_image': False,
'following': None,
'listed_count': 3,
......
'timestamp_ms': '1569959996453',
'favorited': False,
'is_quote_status': False,
'coordinates': None,
'contributors': None,
'place': {'place_type': 'city',
'attributes': {},
'bounding_box': {'coordinates': [[[72.436739, 22.923256],
[72.436739, 23.104662],
[72.703725, 23.104662],
[72.703725, 22.923256]]],
'type': 'Polygon'},
'full_name': 'Ahmadabad City, India',
'country': 'India',
'url': 'https://api.twitter.com/1.1/geo/id/272983f6b52c196e.json',
'country_code': 'IN',
'id': '272983f6b52c196e',
'name': 'Ahmadabad City'}}

我想选择某些键的值,例如"文本"、"用户"键中的"位置"和"地点"中"bounding_box"中的"坐标"。

几个选择都是成功的,但是当我想在"place"的"bounding_box"中选择"坐标"时,它会给我错误:"NoneType"对象不可下标。

这是我的代码: 以下 4 行都有效:

all_id_str = [one_read['id_str'] for one_read in json_read]
all_text = [one_read['text'] for one_read in json_read]
all_coord = [one_read['coordinates'] for one_read in json_read]
all_location = [one_read['user']['location'] for one_read in json_read]

但是以下与"地点"相关的 2 行不起作用:

all_country= [one_read['place']['country'] for one_read in json_read]
all_bbox = [one_read['place']['bounding_box'] for one_read in json_read]

类型错误回溯(上次调用的最近一次( 在

----> 1 all_country= [one_read['place']['country'] for one_read in json_read]
2 all_bbox = [one_read['place']['bounding_box'] for one_read in json_read]

在 (.0( 中

----> 1 all_country= [one_read['place']['country'] for one_read in json_read]
2 all_bbox = [one_read['place']['bounding_box'] for one_read in json_read]

类型错误:"NoneType"对象不可下标

我已经测试了是否有任何单个字典不包含键"place"的/null 值,但它们都返回空 []

[one_read for one_read in json_read if one_read['place'] == 'None']
[one_read for one_read in json_read if one_read['place'] == 'Null']

输出: []

有人可以帮忙吗?

one_read['place']

无效。

你应该做one_read['user']['place']['country']来抓住这个国家

最新更新