结果
json.dumps
是json格式的字符串,因此如果要搜索
p2
你需要做一些字符串匹配。即.
'attributes:[' in p2
会匹配是
在某处
在json中,有一个“attributes”键名,后跟一个数组。这个解决方案并不理想,因为当json字符串的格式不同时(例如使用缩进),它无法处理这种情况。
蟒蛇的方法是检查
y
就像其他答案所暗示的那样。即
('attributes' in y) # True because it exists
(isinstance(y['attributes'], list)) # True because it's a list
最变态的方式就是
假定
这是一个列表,如果你碰到了一个,就要处理一个失败。
我还想在
Marshmallow
序列化库。它旨在处理更复杂的模式验证任务,但您也可以在这里应用它来验证attributes字段是否存在,以及它是否映射到列表。即.
y = { ... } # like before...
from mashmallow import Schema, fields
class AttributesList(Schema):
attributes = fields.List(fields.Dict())
al = AttributesList()
al.dumps(y)