2016-07-03 15 views
9

Jestem bardzo nowy w programowaniu, uczyłem się Pythona z ostatnich 3/4 tygodni i jest to jedno z podanych zadań.csv do konwersji json z pytonem

Wejście

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

Wyjście

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

Próbowałem z kodem jak

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) 

Wyjście dla tego kodu jest jak poniżej

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

Czy ktoś może mi pomóc w tej sprawie. TIA

+0

wejściowy nie jest w formacie CSV. Wynik nie jest prawidłowy json. Masz na myśli listę słownika? '[{A:" 1 ", B:" 2 ", C:" 3 ", D:" 4 "}, {A:" 5 ", B:" 6 ", C:" 7 ", D:" 8 "}]' – falsetru

+0

Przepraszam .. !! Tak, to jest lista dyktafonów – naren

Odpowiedz

16

Zrzut po przetworzeniu całych rzędów.


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) 
+0

Próbowałem tylko, ale to nie zadziałało. moc wyjściowa jest poniżej: [{"A, B, C, D": "1,2,3,4"}, {"A, B, C, D": "5,6,7,8" }, {}, {}] – naren

+0

@naren, testowałem przed wysłaniem tego. Stworzył plik 'test.json' z' [{"A": "1", "C": "3", "B": "2", "D": "4"}, {"A" : "5", "C": "7", "B": "6", "D": "8"}] "jako treść. – falsetru

+0

@naren, http://asciinema.org/a/0l1kc6i09yqx1b0ib2sus6d42 – falsetru

3

Przeczytaj csv, a następnie napisz go krok po kroku.

#Read CSV File 
def read_csv(file, json_file, format): 
    csv_rows = [] 
    with open(file) as csvfile: 
     reader = csv.DictReader(csvfile) 
     title = reader.fieldnames 
     for row in reader: 
      csv_rows.extend([{title[i]:row[title[i]] for i in range(len(title))}]) 
     write_json(csv_rows, json_file, format) 

#Convert csv data into json and write it 
def write_json(data, json_file, format): 
    with open(json_file, "w") as f: 
     if format == "pretty": 
      f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': '),encoding="utf-8",ensure_ascii=False)) 
     else: 
      f.write(json.dumps(data)) 

Przeczytaj pełną wersję article.

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)) 
0

Można próbować go przy użyciu tego kodu:

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 
0

CSV Konwersja do formatu JSON Pythona

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