1

I am tring to create a json file with my lists in my python code:

I have

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

I would like this to return in the json file like

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

Is it possible to do that? I tried to do a for loop like this:

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

and json.dumps() but it don't work ... maybe I have to do a tuple with (user.value[0], wallet_amount.value[0]) ?

for peoples who try to do the reverse thing : How to create a Python list from a JSON object?

I would like to thank all those who helped me and who participate in the learning of all.

quamrana
  • 37,849
  • 12
  • 53
  • 71

3 Answers3

2

Convert the lists to list of dictionaries and dump this to the file

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}]
Guy
  • 46,488
  • 10
  • 44
  • 88
  • thakns ! it work ! I would really struggle, is it possible de do a rest api with this method ? i mean like : @app.route(/wallet, method: GET) => return a json file with this values ? thanks again for your help – ax3l Garcia Sep 08 '22 at 11:34
  • @ax3lGarcia I think you are looking for something like https://stackoverflow.com/questions/13081532/return-json-response-from-flask-view – Guy Sep 08 '22 at 12:15
  • finaly i just do like that : resp = (open('file.json' , 'r') and return resp.read() and it work thanks because without you i was conviced that i was necessary to use jsonify – ax3l Garcia Sep 08 '22 at 12:31
1

Another simple solution, using enumerate:

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))
Liutprand
  • 527
  • 2
  • 8
  • 1
    `for user_id, amount in zip(arr_of_id_by_user, arr_of_wallet_amount)` is more "pythonic" way to iterate over multiple sequences. – Olvin Roght Sep 07 '22 at 07:48
  • I agree, I was just proposing an alternative solution, maybe less "pythonic" but perhaps more clear then using the zip function. – Liutprand Sep 07 '22 at 07:51
0

Python List to JSON Array

list_example = ["Mango", 1, 3,6, "Oranges"];
print(json.dumps(list_example))
cottontail
  • 10,268
  • 18
  • 50
  • 51
Joel Wembo
  • 814
  • 6
  • 10