【发布时间】:2022-01-24 19:49:29
【问题描述】:
在循环遍历此 json 对象 content 时遇到一些困难。
json文件是这样的:
[{'archived': False,
'cache_ttl': None,
'collection': {'archived': False,
'authority_level': None,
'color': '#509EE3',
'description': None,
'id': 525,
'location': '/450/',
'name': 'eaf',
'namespace': None,
'personal_owner_id': None,
'slug': 'eaf'},
'collection_id': 525,
'collection_position': None,
'created_at': '2022-01-06T20:51:17.06376Z',
'creator_id': 1,
'database_id': 4,
}, ... ]
我想遍历列表中的每个字典,检查集合是否为空,然后对于每个集合,如果位置等于'/450/',则返回将该字典附加到列表中。
我的代码如下。
content = json.loads(res.text)
for q in content:
if q['collection']:
for col in q['collection']:
if col['location'] == '/450/':
data.append(q)
print(data)
玩过它后,我不断收到ValueError: too many values to unpack (expected 2) 或 TypeError: string indices must be integers
非常感谢对我的结构的任何帮助。
免责声明:
我之前把它写成一个列表理解,它就像一个魅力,但它不再起作用了,因为我现在需要检查collection 是否为空。
我之前是怎么写的:
content = [ x for x in content if x['collection']['location'] == '/450/']
【问题讨论】:
-
你得到
TypeError: string indices must be integers因为col是一个字符串,而你正在尝试做col['location']。
标签: python json dictionary for-loop indices