Python:将字典列表转换为 json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21525328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:04:40  来源:igfitidea点击:

Python: converting a list of dictionaries to json

pythonjsonlistdictionary

提问by Apoorv Ashutosh

I have a list of dictionaries, looking some thing like this:

我有一个字典列表,看起来像这样:

list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]

and so on. There may be more documents in the list. I need to convert these to one JSON document, that can be returned via bottle, and I cannot understand how to do this. Please help. I saw similar questions on this website, but I couldn't understand the solutions there.

等等。列表中可能还有更多文档。我需要将这些转换为一个 JSON 文档,该文档可以通过 Bottle 返回,但我无法理解如何执行此操作。请帮忙。我在这个网站上看到了类似的问题,但我无法理解那里的解决方案。

采纳答案by markcial

use json library

使用 json 库

import json
json.dumps(list)

by the way, you might consider changing variable list to another name, listis the builtin function for a list creation, you may get some unexpected behaviours or some buggy code if you don't change the variable name.

顺便说一句,您可能会考虑将变量列表更改为另一个名称,它list是用于创建列表的内置函数,如果您不更改变量名称,您可能会遇到一些意外行为或一些错误代码。

回答by Mohit Rajput

To convert it to a single dictionary with some decided keys value, you can use the code below.

要将其转换为具有某些确定键值的单个字典,您可以使用下面的代码。

data = ListOfDict.copy()
PrecedingText = "Obs_"
ListOfDictAsDict = {}
for i in range(len(data)):
    ListOfDictAsDict[PrecedingText + str(i)] = data[i]

回答by Ramineni Ravi Teja

import json

list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]

Write to json File:

写入 json 文件:

with open('/home/ubuntu/test.json', 'w') as fout:
    json.dump(list , fout)

Read Json file:

读取 Json 文件:

with open(r"/home/ubuntu/test.json", "r") as read_file:
    data = json.load(read_file)
print(data)
#list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]

回答by Akhilesh Joshi

response_json = ("{ \"response_json\":" + str(list_of_dict)+ "}").replace("\'","\"")
response_json = json.dumps(response_json)
response_json = json.loads(response_json)