简体   繁体   English

Python:将字典列表转换为 json

[英]Python: converting a list of dictionaries to json

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.我需要将这些转换为一个 JSON 文档,该文档可以通过 Bottle 返回,但我无法理解如何执行此操作。 Please help.请帮忙。 I saw similar questions on this website, but I couldn't understand the solutions there.我在这个网站上看到了类似的问题,但我无法理解那里的解决方案。

use json library使用 json 库

import json
json.dumps(list)

by the way, you might consider changing variable list to another name, list is 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是用于创建list的内置函数,如果您不更改变量名称,您可能会遇到一些意外行为或一些错误代码。

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]}]
response_json = ("{ \"response_json\":" + str(list_of_dict)+ "}").replace("\'","\"")
response_json = json.dumps(response_json)
response_json = json.loads(response_json)

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM