首页 > 解决方案 > Converting a CSV file into a JSON file using python

问题描述

I have been trying to convert a csv file into json with python 3. I want to convert a csv file which would look more or less like this:

Key ,Field_1 ,Field_2 ...
0   ,a       ,e       ...
1   ,b       ,f       ...
2   ,c       ,g       ...
3   ,d       ,h       ...

Into a json file that is structured Key : [Field_1, Field_2, ...]

So that the csv above would end up looking like

{
  "0" : ["a", "e", ...]
  "1" : ["b", "f", ...]
  "2" : ["c", "g", ...]
  "3" : ["d", "h", ...]
}

I have been trying to use the code below but have been unable to fill in the missing parts, like assigning each value to their corresponding part on the json file.

csv = pd.read_csv("file.csv")
n = 0
length = # number of keys
for i in csv:
    if n == 0:
        for y in range(lentgh):
            # Assign as the header
    else:
        for y in range(length):
            # Assign as the properties
    n += 1

Also Im trying to make it so that all new data is attached at the end of the json file automatically.

标签: pythonjsonpython-3.xcsvconverters

解决方案


仍然会json缩进值列表,但这会将您的 csv 转换为您想要的字典并将其附加到 json 文件

import csv
import json

with open('blah.csv') as f:
    reader = csv.reader(f)
    next(reader)
    d = dict((rows[0], rows[1:]) for rows in reader)

with open('blah.json', 'a') as f:
    json.dump(d, f, indent=4)

推荐阅读