python - 如何从 python 中的 JSON 对象中删除带有值的空键?

标签 python django

我有一个 JSON 对象,我想在其中删除值为我的 JSON 的空键。请给我一个解决方案,我怎样才能从对象中删除带有键和值的空属性,并且可以获得没有空键的数据

更新:

if request.method == 'POST': 
    all_products = request.data['products']
    
    db = CategoriesActiveORM.get_connection()
    keywords = db.table('categories'). \
        select('products', db.raw('count(*) as total')). \
        where_not_null('products'). \
        group_by('products'). \
        order_by('total', 'desc'). \
        limit(4). \
        get()

    total = keywords.sum('total')
    industries = {}
    for key in keywords:
        industries[key['products']] = round(int(key['total']) / total * 100, 2)
    
    print('industries', industries)
    
    industries = industries.pop("null", None)   

    print('industries', industries)
    
    industries.pop("null", None)
    rint('industries', industries)

    return JsonResponse(industries)

打印 1:

{
    "null": 87.37,
    " Product1": 4.95,
    " Product2": 4.44,
    " Product3": 3.24
}

打印 2:

None

打印 3:

{
    "null": 87.37,
    " Product1": 4.95,
    " Product2": 4.44,
    " Product3": 3.24
}

最佳答案

如果你想从字典中删除一个键,这里已经回答了一个类似的问题: How can I remove a key from a Python dictionary?

您正在为刚刚从字典中弹出的项目分配行业。

解决方案 A

要解决此问题,您不能将弹出的项目分配给 industries

只需删除 industries = 如下:

之前

industries = industries.pop("null", None)

之后

industries.pop("null", None)

这应该会给你想要的结果。

方案B

如果这不起作用,请尝试使用 del,如下所示:

del industries["null"]

编辑

您似乎忘记了对象中 None 键上的引号,这似乎已经解决了您的问题。

关于python - 如何从 python 中的 JSON 对象中删除带有值的空键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71324861/

相关文章:

Django:user.has_perm 始终为 true 并且用户不是 super 用户。为什么?

python - 防止docker-compose在使用构建镜像时重新安装requirements.txt

python - 如何在Python中生成2个数字之间给定小数点的随机数?

python - Django:在基于类的 View 中访问变量

django url 标签性能

django - 如何限制来自 GraphQL API 端点的匿名用户?

python - Django 中的 "auth.User"是做什么的?

python - 正确地将 JSON 转换并格式化为 CSV?

php - 像 PHP 一样运行 Python 脚本

python - 字典列表中的 Pandas 数组