Home > Enterprise >  How can I remove null keys with values from JSON object in python?
How can I remove null keys with values from JSON object in python?

Time:03-03

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

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:

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

Print 2:

None

Print 3:

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

CodePudding user response:

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?

You are assigning industries to the item you just popped from the dictionary.

Solution A

To fix this you must not assign the popped item to industries.

Just remove the industries = as follows:

Before

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

After

industries.pop("null", None)

This should give you the result you desire.

Solution B

If that didn't work try using del as follows:

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.

  • Related