簡體   English   中英

如何將 CSV 文件轉換為多行 JSON?

[英]How to convert CSV file to multiline JSON?

這是我的代碼,非常簡單的東西......

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:使用類似for line in csvfile: ,然后用reader = csv.DictReader( line, fieldnames)它下面運行我的代碼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)

json.dumps() 文檔

你可以試試這個

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)

我看到這是舊的,但我需要來自 SingleNegationElimination 的代碼,但是我對包含非 utf-8 字符的數據有問題。 這些出現在我不太關心的領域,所以我選擇忽略它們。 然而,這需要一些努力。 我是 python 的新手,所以經過一些試驗和錯誤,我讓它工作了。 該代碼是 SingleNegationElimination 的副本,帶有 utf-8 的額外處理。 我試圖用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

indent參數添加到json.dumps

 data = {'this': ['has', 'some', 'things'],
         'in': {'it': 'with', 'some': 'more'}}
 print(json.dumps(data, indent=4))

另請注意,您可以簡單地將json.dump與打開的jsonfile

json.dump(data, jsonfile)

如何使用 Pandas 將 csv 文件讀入 DataFrame ( pd.read_csv ),然后根據需要操作列(刪除它們或更新值),最后將 DataFrame 轉換回 JSON ( pd.DataFrame.to_json )。

注意:我還沒有檢查這會有多高效,但這絕對是操作大型 csv 並將其轉換為 json 的最簡單方法之一。

作為對@MONTYHS 答案的輕微改進,遍歷一組字段名:

import csv
import json

csvfilename = 'filename.csv'
jsonfilename = csvfilename.split('.')[0] + '.json'
csvfile = open(csvfilename, 'r')
jsonfile = open(jsonfilename, 'w')
reader = csv.DictReader(csvfile)

fieldnames = ('FirstName', 'LastName', 'IDNumber', 'Message')

output = []

for each in reader:
  row = {}
  for field in fieldnames:
    row[field] = each[field]
output.append(row)

json.dump(output, jsonfile, indent=2, sort_keys=True)
def read():
    noOfElem = 200  # no of data you want to import
    csv_file_name = "hashtag_donaldtrump.csv"  # csv file name
    json_file_name = "hashtag_donaldtrump.json"  # json file name

    with open(csv_file_name, mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        with open(json_file_name, 'w') as json_file:
            i = 0
            json_file.write("[")
            
            for row in csv_reader:
                i = i + 1
                if i == noOfElem:
                    json_file.write("]")
                    return

                json_file.write(json.dumps(row))

                if i != noOfElem - 1:
                    json_file.write(",")

改變上面三個參數,一切就搞定了。

使用 pandas 和 json 庫:

import pandas as pd
import json
filepath = "inputfile.csv"
output_path = "outputfile.json"

df = pd.read_csv(filepath)

# Create a multiline json
json_list = json.loads(df.to_json(orient = "records"))

with open(output_path, 'w') as f:
    for item in json_list:
        f.write("%s\n" % item)
import csv
import json
csvfile = csv.DictReader('filename.csv', 'r'))
output =[]
for each in csvfile:
    row ={}
    row['FirstName'] = each['FirstName']
    row['LastName']  = each['LastName']
    row['IDNumber']  = each ['IDNumber']
    row['Message']   = each['Message']
    output.append(row)
json.dump(output,open('filename.json','w'),indent=4,sort_keys=False)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM