Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert csv to json in python?

Tags:

python

json

csv

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

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?

like image 642
naren Avatar asked Jul 03 '16 12:07

naren


People also ask

Can we convert CSV to JSON?

JSON requires the data to be in a structure or a schema, which are not compatible with the CSV file structure. CSV to JSON Converter tool is designed to convert CSV files into JSON format in a very easy manner.


2 Answers

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)
like image 156
falsetru Avatar answered Oct 25 '22 19:10

falsetru


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

like image 3
Antony Fuentes Avatar answered Oct 25 '22 17:10

Antony Fuentes