如何在python中将csv转换为json?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38170071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:27:04  来源:igfitidea点击:

How to convert csv to json in python?

pythonjsoncsv

提问by naren

I'm very new to programming, have been learning python from past 3/4 weeks and this is one of the assignments given.

我对编程很陌生,过去 3/4 周一直在学习 python,这是给定的作业之一。

Input

输入

A, B, C, D
1, 2, 3, 4
5, 6, 7, 8

Output

输出

{{A:"1", B:"2", C:"3", D:"4"}, {A:"5", B:"6", C:"7", D:"8"}}

I've been trying with the code as:

我一直在尝试使用以下代码:

import csv
import json

csvfile = open('test.csv','r')
jsonfile = open('test.json','w')

x = ("a","b","c","d")

reader = csv.DictReader(csvfile, x)
for row in reader:
    json.dump(row, jsonfile)

The output for this code comes as below:

此代码的输出如下:

{"a": "1", "null": ["5", "6", "7", "8", "9"], "c": "3", "b": "2", "d": "4"}

Can anyone help me on this?

谁可以帮我这个事?

回答by falsetru

Dump after processing whole rows.

处理整行后转储。



import csv
import json

with open('test.csv') as f:
    reader = csv.DictReader(f)
    rows = list(reader)

with open('test.json', 'w') as f:
    json.dump(rows, f)

回答by Antony Fuentes Artavia

For those who like one-liners:

对于那些喜欢单线的人:

import csv
import json

json_data = [json.dumps(d) for d in csv.DictReader(open('file.csv'))]

Checkout this fiddle for a working example: https://pyfiddle.io/fiddle/5992b8f4-552f-4970-91b6-a52cdee16ebc/?i=true

查看这个小提琴的工作示例:https: //pyfiddle.io/fiddle/5992b8f4-552f-4970-91b6-a52cdee16ebc/?i=true

回答by davland7

Convert CSV to Json Python

将 CSV 转换为 Json Python

import csv
import urllib2

url = '<YOURCSVURL>'
response = urllib2.urlopen(url)
cr = csv.reader(response)

line = {}
data = []

for index, row in enumerate(cr):
    if index:
        for index, col in enumerate(row):
            line[name[index]] = col

        data.append(line.copy())
    else:
        name = row

print data

回答by Moises Rezonzew

import csv
import json

# Constants to make everything easier
CSV_PATH = './csv.csv'
JSON_PATH = './json'

# Reads the file the same way that you did
csv_file = csv.DictReader(open(CSV_PATH, 'r'))

# Created a list and adds the rows to the list
json_list = []
for row in csv_file:
    json_list.append(row)

# Writes the json output to the file
file(JSON_PATH, 'w').write(json.dumps(json_list))

回答by Kenstars

You can attempt it using this code :

您可以尝试使用此代码:

def inputfunction(lists):
 tmpdict = {}
 for element_index in range(len(lists)):
     tmpdict[headers[elementindex]] = lists[element_index]
 return tmpdict

def run(filename):
 filelist = [eachline.split(',') for eachline in open(inputfile,'r')]
 headers = filelist[0]
 values = filelist[1:]
 finallist = []
 for lists in values:
     finallist.append(inputfunction(lists))
 return finallist