JSON文件选择键和值g

2024-05-29 03:01:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我的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'}}

我想选择某些键的值,例如“用户”键中的“文本”、“位置”和“地点”中的“边界框”中的“坐标”

有几个选择是成功的,但是当我想在“place”中的“bounding\u box”中选择“coordinates”时,它给出了一个错误:“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]

但以下两行与“地点”相关的内容不起作用:

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]

TypeError回溯(最近一次调用) 在

----> 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]

TypeError:“NoneType”对象不可订阅

我测试了是否有任何一个字典包含键“place”的none/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']

输出: []

有人能帮忙吗


Tags: inboxnoneidjsonfalseforread

热门问题