여기 내 코드, 정말 간단한 것들이 있습니다.
import csv
import json
csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')
fieldnames = ("FirstName","LastName","IDNumber","Message")
reader = csv.DictReader( csvfile, fieldnames)
out = json.dumps( [ row for row in reader ] )
jsonfile.write(out)
일부 필드 이름을 선언하고 리더는 CSV를 사용하여 파일을 읽고 파일 이름을 사용하여 파일을 JSON 형식으로 덤프합니다. 여기에 문제가 있습니다 …
CSV 파일의 각 레코드는 다른 행에 있습니다. JSON 출력이 같은 방식이기를 원합니다. 문제는 모든 것을 하나의 거대하고 긴 줄에 버린다는 것입니다.
나는 for line in csvfile:
다음 과 같은 것을 사용하고 reader = csv.DictReader( line, fieldnames)
각 줄을 반복 하는 코드를 아래에서 실행 하려고 시도했지만 한 줄에서 전체 파일을 수행 한 다음 다른 줄에서 전체 파일을 반복합니다 … 줄이 떨어질 때까지 계속됩니다. .
이 문제를 해결하기위한 제안 사항이 있습니까?
편집 : 명확히하기 위해 현재 : (1 행의 모든 레코드)
[{"FirstName":"John","LastName":"Doe","IDNumber":"123","Message":"None"},{"FirstName":"George","LastName":"Washington","IDNumber":"001","Message":"Something"}]
내가 찾는 것 : (2 줄에 2 개의 레코드)
{"FirstName":"John","LastName":"Doe","IDNumber":"123","Message":"None"}
{"FirstName":"George","LastName":"Washington","IDNumber":"001","Message":"Something"}
각 개별 필드가 들여 쓰기 / 별도의 줄에있는 것이 아니라 각 레코드가 자체 줄에 있습니다.
샘플 입력.
"John","Doe","001","Message1"
"George","Washington","002","Message2"
답변
원하는 출력의 문제는 유효한 json 문서가 아니라는 것입니다. 그것은 json 문서 의 흐름입니다 !
필요하다면 괜찮습니다.하지만 출력에서 원하는 각 문서에 대해 json.dumps
.
문서를 분리하려는 줄 바꿈이 해당 문서에 포함되어 있지 않으므로 직접 제공해야합니다. 따라서 json.dump에 대한 호출에서 루프를 꺼내서 작성된 각 문서에 대한 개행 문자를 삽입하면됩니다.
import csv
import json
csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')
fieldnames = ("FirstName","LastName","IDNumber","Message")
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
json.dump(row, jsonfile)
jsonfile.write('\n')
답변
다음 예제를 통해 Pandas DataFrame을 사용하여이를 수행 할 수 있습니다.
import pandas as pd
csv_file = pd.DataFrame(pd.read_csv("path/to/file.csv", sep = ",", header = 0, index_col = False))
csv_file.to_json("/path/to/new/file.json", orient = "records", date_format = "epoch", double_precision = 10, force_ascii = True, date_unit = "ms", default_handler = None)
답변
@SingleNegationElimination의 응답을 가져와 파이프 라인에서 사용할 수있는 세 줄로 단순화했습니다.
import csv
import json
import sys
for row in csv.DictReader(sys.stdin):
json.dump(row, sys.stdout)
sys.stdout.write('\n')
답변
import csv
import json
file = 'csv_file_name.csv'
json_file = 'output_file_name.json'
#Read CSV File
def read_CSV(file, json_file):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
field = reader.fieldnames
for row in reader:
csv_rows.extend([{field[i]:row[field[i]] for i in range(len(field))}])
convert_write_json(csv_rows, json_file)
#Convert csv data into json
def convert_write_json(data, json_file):
with open(json_file, "w") as f:
f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': '))) #for pretty
f.write(json.dumps(data))
read_CSV(file,json_file)
답변
당신은 이것을 시도 할 수 있습니다
import csvmapper
# how does the object look
mapper = csvmapper.DictMapper([
[
{ 'name' : 'FirstName'},
{ 'name' : 'LastName' },
{ 'name' : 'IDNumber', 'type':'int' },
{ 'name' : 'Messages' }
]
])
# parser instance
parser = csvmapper.CSVParser('sample.csv', mapper)
# conversion service
converter = csvmapper.JSONConverter(parser)
print converter.doConvert(pretty=True)
편집하다:
더 간단한 접근
import csvmapper
fields = ('FirstName', 'LastName', 'IDNumber', 'Messages')
parser = CSVParser('sample.csv', csvmapper.FieldMapper(fields))
converter = csvmapper.JSONConverter(parser)
print converter.doConvert(pretty=True)
답변
indent
매개 변수 추가json.dumps
data = {'this': ['has', 'some', 'things'],
'in': {'it': 'with', 'some': 'more'}}
print(json.dumps(data, indent=4))
또한 json.dump
open으로 간단히 사용할 수 있습니다 jsonfile
.
json.dump(data, jsonfile)
답변
나는 이것이 오래되었다고 생각하지만 SingleNegationElimination의 코드가 필요했지만 utf-8이 아닌 문자를 포함하는 데이터에 문제가 있습니다. 이것들은 내가 지나치게 신경 쓰지 않는 분야에 나타나서 무시하기로 결정했습니다. 그러나 그것은 약간의 노력이 필요했습니다. 나는 파이썬을 처음 접했기 때문에 시행 착오를 거쳐 작동했습니다. 이 코드는 utf-8을 추가로 처리 한 SingleNegationElimination의 복사본입니다. https://docs.python.org/2.7/library/csv.html로 시도했지만 결국 포기했습니다. 아래 코드가 작동했습니다.
import csv, json
csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')
fieldnames = ("Scope","Comment","OOS Code","In RMF","Code","Status","Name","Sub Code","CAT","LOB","Description","Owner","Manager","Platform Owner")
reader = csv.DictReader(csvfile , fieldnames)
code = ''
for row in reader:
try:
print('+' + row['Code'])
for key in row:
row[key] = row[key].decode('utf-8', 'ignore').encode('utf-8')
json.dump(row, jsonfile)
jsonfile.write('\n')
except:
print('-' + row['Code'])
raise