chraebsli
chraebsli

Reputation: 410

Save JSON data from lists in python

I want to save some data automatically in a json file. Here my data:

names = ['name1','name2','name3','name2']
number1 = [43,32,12,12]
number2 = [3,6,6,3]
dates = ['01.03.2021 13:05:59','01.03.2021 13:46:04','01.03.2021 14:05:59','01.03.2021 13:30:04']

What I want is something like this:

{
    "items":[
        {
        "time": "01.03.2021 13:54:21",
        "name": "name1",
        "age": 43,
        "coins": 3
        },
        {
        "time": "01.03.2021 13:46:04",
        "name": "name2",
        "age": 32,
        "coins": 6
        }
        ...
    ]
}

The elements for name1 are with [0], name2 has them with [1],etc.)

And the keys or the structure doesn't matter it only has to make sense.

Upvotes: 1

Views: 833

Answers (2)

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11083

Try this in one line using zip():

result = {'items':[{'time':i[0],'name':i[1], 'age':i[2], 'coins':i[3]} for i in zip(dates,names,number1,number2)]}

the result will be:

{'items': [
  {'time': '01.03.2021 13:05:59', 'name': 'name1','age': 43,'coins': 3},
  {'time': '01.03.2021 13:46:04', 'name': 'name2', 'age': 32, 'coins': 6},
  {'time': '01.03.2021 14:05:59', 'name': 'name3', 'age': 12, 'coins': 6},
  {'time': '01.03.2021 13:30:04', 'name': 'name2', 'age': 12, 'coins': 3}
]}

Upvotes: 5

Krishna Chaurasia
Krishna Chaurasia

Reputation: 9580

Simply create a list of dictionaries and use json for writing to file:

output = []
for name, num1, num2, date in zip(names, number1, number2, dates):
    dic = dict()
    dic["time"] = date
    dic["name"] = name
    dic["age"] = num1
    dic["coins"] = num2
    output.append(dic)

data = {"items": output}
import json
with open('out.json', 'w') as outfile:
    json.dump(data, outfile)

Note: dic object could be removed but it looks readable that way.

Content of out.json:

{"items": [{"time": "01.03.2021 13:05:59", "name": "name1", "age": 43, "coins": 3}, {"time": "01.03.2021 13:46:04", "name": "name2", "age": 32, "coins": 6}, {"time": "01.03.2021 14:05:59", "name": "name3", "age": 12, "coins": 6}, {"time": "01.03.2021 13:30:04", "name": "name2", "age": 12, "coins": 3}]}

Upvotes: 2

Related Questions