如何使Django输出一个jsonified字典列表?

2024-06-17 13:33:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个列表中有一本词典的输出

[{'actors': 'Amy Poehler, Tina Fey, John Cena, Maya Rudolph',
'categories': {'id': 225, 'name': 'Comedy', 'parent_id': 2}, ...

我希望引号是",而不是'

我正在开发的应用程序应该返回JSON,我相信对于JSON来说'是一个字符,所以它会破坏它。工作okay!还有not okay!你知道吗

更新

我试过使用json.dumps,但它是escaped


Tags: idjson列表actorsjohn词典categoriesmaya
2条回答

您可以使用json lib

import json

array = [{'actors': 'Amy Poehler, Tina Fey, John Cena, Maya Rudolph', ...
print(json.dumps(array))

正如yedpodtrzitko提到的,Django应该为您序列化信息—您不必首先将其转换为字符串。你知道吗

From the docs

content = JSONRenderer().render(serializer.data)
content
# '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'

所以看起来无论你从序列化程序中得到什么,都应该是一个包含所有内容的简单的ol'字典。我想如果你这么做了

content = JSONRenderer().render({'quests': [{'Sir Galahad': 'I seek the grail',
                                             'King Arthur': 'I seek the grail'}])

它将转储适当的JSON字符串

相关问题 更多 >