gpt4 book ai didi

python - 检查 json 父值是否为空

转载 作者:行者123 更新时间:2023-12-01 05:09:31 25 4
gpt4 key购买 nike

我可以使用什么方法来确定 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":[]}

最佳答案

在您的示例中,您的 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'

关于python - 检查 json 父值是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24472387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com