繁体   English   中英

如何从 python 的列表中创建 json 文件?

[英]How to create a json file from list in python?

我想用我的 python 代码中的列表创建一个 json 文件:

我有

arr_of_id_by_user = [1, 2, 3]
arr_of_wallet_amount = [100,3400,200]

我希望这可以在 json 文件中返回,例如

jsonfile = [{
    "user" : 1,
    "wallet amount": 100
},
{
    "user" : 2,
    "wallet amount": 3400
},
{
    "user" : 3,
    "wallet amount": 200
}]

有可能这样做吗? 我试图做一个这样的for循环:

for elements in arr_of_id_by_user:
        return jsonify({
            "id": elements
        })

json.dumps()但它不起作用......也许我必须用(user.value[0], wallet_amount.value[0])做一个元组?

对于试图做相反事情的人: 如何从 JSON object 中创建 Python 列表?

我要感谢所有帮助过我并参与所有人学习的人。

将列表转换为字典列表并将其转储到文件中

arr_of_id_by_user = [1, 2, 3]
arr_of_wallet_amount = [100, 3400, 200]
with open('file.json', 'w') as file:
    json.dump([{'user': id, 'wallet amount': amount} for id, amount in zip(arr_of_id_by_user, arr_of_wallet_amount)], file)

file.json

[{"user": 1, "wallet amount": 100}, {"user": 2, "wallet amount": 3400}, {"user": 3, "wallet amount": 200}]

另一个简单的解决方案,使用枚举:

import json

arr_of_id_by_user = [1, 2, 3]
arr_of_wallet_amount = [100,3400,200]

jsonfile=[]

for index, value in enumerate(arr_of_id_by_user):
    jsonfile.append({
        "user": value,
        "waller_amount": arr_of_wallet_amount[index]
    }) 

print (json.dumps(jsonfile, indent=4))
Python List to JSON Array

list_example = ["Mango", 1, 3,6, "Oranges"];
print(json.dumps(list_example))

暂无
暂无

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

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