如何在Python中将列表字典转换为JSON?

3

我有一个JSON列表,希望将它们转换为单个JSON。我尝试使用json.dumps,但结果仍然是一个JSON列表。

"response":[{"sent":46},{"drafts":2},{"completed":48},{"pending":1}]

我希望您以这种形式呈现。
"response":{"sent":46,"drafts":2,"completed":48,"pending":1}

你能帮我处理这个问题吗?


1
所以,你有一个字典列表,想要将它们合并成一个字典? - DYZ
1
假设所有的键都是唯一的,你可以使用字典推导式来实现,例如 {"response": {k: v for item in data['response'] for k, v in item.items()}} - Chris Doyle
请问您能否指导一下,我想将字典列表转换为一个字典。 - Mahima K
@ChrisDoyle,嘿,谢谢,我收到了。 - Mahima K
{'response': [{'sent': 46}, {'drafts': 2}, {'completed': 48}, {'pending': 1}]} {'响应': [{'发送': 46}, {'草稿': 2}, {'已完成': 48}, {'待处理': 1}]} - Hayat
你没有“一组json” - json是一种文本格式,而不是数据类型。你拥有的是一个字典,其中“response”键是一个字典列表。 - bruno desthuilliers
2个回答

0

你可以使用:

from itertools import chain
r = {"response" :[{"sent":46},{"drafts":2},{"completed":48},{"pending":1}]}


r['response'] = dict(chain(*map(dict.items, r['response'])))
# same with:
# r['response'] = dict(chain.from_iterable(map(dict.items, r['response'])))
r

输出:

{'response': {'sent': 46, 'drafts': 2, 'completed': 48, 'pending': 1}}

或者您可以使用字典推导式:

r['response'] = {k: v for d in r['response'] for k, v in d.items()}

输出:

{'response': {'sent': 46, 'drafts': 2, 'completed': 48, 'pending': 1}}

0

你可以使用

json_obj = {"response":[{"sent":46},{"drafts":2},{"completed":48},{"pending":1}]}
{k: {list(i.keys())[0]: list(i.values())[0] for i in v} for k, v in json_obj.items()}

这将输出

{'response': {'sent': 46, 'drafts': 2, 'completed': 48, 'pending': 1}}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接