社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在Python3.x中查找数组是否存在且不为空

Captain Nemo • 5 年前 • 1659 次点击  

我想检查json输入中是否存在元素,下面的代码片段似乎可以工作

import json
y = {
    "attributes": [
        {
            "name": "test"
        }
    ]
}

p2 = json.dumps(y)

if 'attributes' not in p2:
    print("not found")
else:
    print("found")

我现在想检查attributes元素是否是list类型和list大小

什么是蟒蛇式的方法来达到这个目的?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/44204
 
1659 次点击  
文章 [ 4 ]  |  最新文章 5 年前
Charles Landau
Reply   •   1 楼
Charles Landau    6 年前

在你的代码片段中 p2 是一个字符串( json.dumps 皈依者 y 到字符串中的有效json对象)

isinstance 是检查的首选方式,因此您可以使用:

if isinstance(y['attributes'], list):
    len(y['attributes'])
Nihal
Reply   •   2 楼
Nihal    6 年前

使用 isinstance() 要检查类型,它将返回布尔值

y = {
    "attributes": [
        {
            "name": "test"
        }
    ]
}

# p2 = json.dumps(y)

if 'attributes' not in y:
    print("not found")

else:
    print(y['attributes'])
    print(isinstance(y['attributes'], list))
    if isinstance(y['attributes'], list):
        print('its a list')
        print(len(y['attributes']))
    print("found")

输出:

[{'name': 'test'}]
True
its a list
1
found
Andrew F
Reply   •   3 楼
Andrew F    6 年前

结果 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)
DirtyBit
Reply   •   4 楼
DirtyBit    6 年前
json_data = json.dumps({
    "attributes": [
        {
            "name": "test"
        }
    ]
})


item_dict = json.loads(json_data)
print(type((item_dict['attributes'])))    # list
print(len((item_dict['attributes'][0])))     # 1