如何在python中将列表转换为json

问题描述 投票:0回答:2

具有值列表

test = ["mark","will","john"]


使用for循环如何将其像这样转换为JSON

test =[{"name":"mark"},{"name":"john"},{"name":"will"}]

尝试过此

for i in test :
    print({"name":i})

python json python-3.x for-loop
2个回答
5
投票

在列表理解中创建字典:

test = ["mark","will","john"]
json_list = [{"name": n} for n in test]

与:

json_list = []
for n in test:
    json_list.append({"name" : n})

然后转储到json

import json
json.dumps(json_list)

0
投票
import json

test =[{"name":"mark"},{"name":"john"},{"name":"will"}]

testJson = json.dumps(test)

print(testJson) 

© www.soinside.com 2019 - 2024. All rights reserved.