检查JSON父值是否为空
我可以用什么方法来检查json中的父值是否为空呢?
基本上,我有一个这样的链接:
catalogue/items.json?category=1&item=scarf
而且这个链接里有超过10个类别。
我想要搜索所有的类别,直到找到json实际上返回了有效的价格索引等等。(即使某个类别里没有这个商品,它仍然会显示这个类别里有多少个商品在json里。)
举个例子:
如果围巾在类别2里存在:
{"total":100,"items":["name":"Scarf", "current":{"price":"122.5"}]}
如果围巾在类别2里不存在:
{"total":100,"items":[]}
1 个回答
2
在你的例子中,你有一个不正确的JSON字符串,但我使用了正确的版本。
import json
#-----
json_str = '''{"total":100,"items":{"name":"Scarf", "current":{"price":"122.5"}}}'''
data = json.loads(json_str)
if 'name' in data['items'] and data['items']['name'].lower() == 'scarf':
print 'There is Scarf'
else:
print 'There is NO Scarf'
#-----
json_str = '''{"total":100,"items":{}}'''
data = json.loads(json_str)
if 'name' in data['items'] and data['items']['name'].lower() == 'scarf':
print 'There is Scarf'
else:
print 'There is NO Scarf'
结果:
There is Scarf
There is NO Scarf
编辑:正如karthikr所建议的,你可以使用
if data.get('items', {}).get('name', '').lower() == 'scarf':
print 'There is Scarf'
else:
print 'There is NO Scarf'