1

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.

2 Answers 2

5

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}
]}
Sign up to request clarification or add additional context in comments.

Comments

2

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}]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.