18

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?

2
  • Input is not csv. Output is not valid json. Do you mean list of dictionary? [{A:”1”, B:”2”, C:”3”, D:”4”}, {A:”5”, B:”6”, C:”7”, D:”8”}] Commented Jul 3, 2016 at 12:48
  • i'm sorry..!!yes it's list of dictonary Commented Jul 3, 2016 at 12:49

5 Answers 5

36

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

8 Comments

i just tried that but it didn't work. output is as below [{"A,B,C,D": "1,2,3,4"}, {"A,B,C,D": "5,6,7,8"}, {}, {}]
@naren, I tested before post this. It created a file test.json with [{"A": "1", "C": "3", "B": "2", "D": "4"}, {"A": "5", "C": "7", "B": "6", "D": "8"}] as a content.
got it, thanq very much @falsetru , trust your guidence will make me excel in python
@naren, Your input file mismatch with the input in the question.
@falsetru aren't you reinventing the DictReader? Thanks.
|
4

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

1 Comment

This approach makes my numeric value(int, float) of each key to string. Any way to fix this?
0
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))

Comments

0

Convert CSV to 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

Comments

-3

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

2 Comments

The code in your answer isn't indented properly. Also, the return you have in that for loop at the end of the run() function will only allow the loop to execute one iteration.
1: Not properly indented. 2: You are just creating a dictionary of every list which is not a JSON format.3: You have to pass "headers" also an argument in your 'input function" 4: In the run function you have to change "filename "parameter to "inputfile" or vice-versa.

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.