简体   繁体   中英

How to populate a json file from a list in python

I got a CSV file that I want to rearange in a specific manner and then save as JSON.

I've been able to put the information från the csv file into python lists. The problem arise when I try to populate the Json file. I don't understand how to add the lists content to the JSON file.

CSV file:

2010.03.01,00:00,1.0,1.1
2010.03.01,04:00,2.0,2.1
2010.03.01,08:00,3.0,3.1

Desired JSON outcome:

{"Base number":23,"In stock":"Yes","timestamp":[1267398000,1267412400,1267426800],"float1":[1.0,2.0,3.0],"float2":[1.1,2.1,3.1]}

My phython code:

import csv
import json
import datetime

dates = []
float1 = []
float2 = []

with open(csvFile.csv) as csvDataFile:
    csvReader = csv.reader(csvDataFile)
    for row in csvReader:
        #Date and time to timestamp
        timestamp = int(datetime.datetime.strptime(' '.join([row[0], row[1]]), '%Y.%m.%d %H:%M').timestamp())
        dates.append(timestamp)

        #Float value
        float1.append(float(row[2]))
        float2.append(float(row[3]))

data = {
    "Base number": 23,
    "In stock": "Yes",
}
with open(jsonFile.json, 'w') as outfile:
    json.dump(data, outfile)

It seems like you're almost there. You can just update the data dictionary like so:

data = {
    "Base number": 23,
    "In stock": "Yes",
    "float1": float1,
    "float2": float2,
    "timestamp": dates
}

The json dump should contain the lists you created now. Also make sure that you open the json file correctly (just changing jsonFile.json to "jsonFile.json" should work)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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