我有一个 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/