简体   繁体   English

如何从 python 中删除值为 JSON object 的 null 键?

[英]How can I remove null keys with values from JSON object in python?

I have a JSON object in which I want to remove the null key with the value that is my JSON. Please give me a solution how can I remove the null attribute with key and value from the object and can get without null keys data我有一个 JSON object,其中我想删除 null 键,其值为我的 JSON。请给我一个解决方案,如何从 8828299540218888 键中删除带有键和值的 null 属性,并且可以在没有 88839 的情况下获取 1

UPDATE:更新:

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)

Print 1:打印 1:

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

Print 2:打印 2:

None

Print 3:打印 3:

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

If you are looking to delete a key from the dict a similar question has been answered here: How can I remove a key from a Python dictionary?如果你想从字典中删除一个键,这里已经回答了一个类似的问题: How can I remove a key from a Python dictionary?

You are assigning industries to the item you just popped from the dictionary.您正在将行业分配给您刚刚从字典中弹出的项目。

Solution A溶液A

To fix this you must not assign the popped item to industries .要解决此问题,您不得将弹出的项目分配给industries

Just remove the industries = as follows:只需删除industries =如下:

Before

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

After

industries.pop("null", None)

This should give you the result you desire.这应该会给你你想要的结果。

Solution B溶液B

If that didn't work try using del as follows:如果这不起作用,请尝试使用del ,如下所示:

del industries["null"]

EDIT编辑

It seems like you forgot the quotations marks on the None key in the object, that seems to have solved your problem.好像你忘记了 object 中None键上的引号,这似乎已经解决了你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM