我在 CVS 檔案中有 JSON 資料,我需要將其分解為單獨的 JSON 檔案。資料如下所示: {"EventMode":"","CalculateTax":"Y",...。這有多行,我希望每一行都是一個單獨的 JSON 檔案。我使用了 Jatin Grover 提供的將 CVS 決議為 JSON 的代碼:
lcount = 0
out = json.dumps(row)
jsonoutput = open( 'json_file_path/parsedJSONfile' str(lcount) '.json', 'w')
jsonoutput.write(out)
lcount =1
這做得很好,問題是它在 {"EventMode... 之前添加了 "R": " 并在每個元素之間添加了額外的 \ 以及最后的專案。
CVS 檔案的每一行都是有效的 JSON 物件。我只需要將每一行分成一個帶有 .json 擴展名的單獨檔案。
我希望這是有道理的。我對這一切都很陌生。
uj5u.com熱心網友回復:
從您的圖片中不清楚您的 CSV 實際是什么樣子。
我用 JSON 行模擬了一個非常小的 CSV 檔案,如下所示:
Request
"{""id"":""1"", ""name"":""alice""}"
"{""id"":""2"", ""name"":""bob""}"
(所有雙引號都用于轉義作為 JSON 一部分的引號)
當我運行這個小腳本時:
import csv
with open('input.csv', newline='') as input_file:
reader = csv.reader(input_file)
next(reader) # discard/skip the fist line ("header")
for i, row in enumerate(reader):
with open(f'json_file_path/parsedJSONfile{i}.json', 'w') as output_file:
output_file.write(row[0])
我得到兩個檔案,json_file_path/parsedJSONfile0.json和json_file_path/parsedJSONfile1.json,它們看起來像這樣:
{"id":"1", "name":"Alice"}
和
{"id":"2", "name":"bob"}
請注意,我沒有使用json.dumps(...),這僅在您從 Python 中的資料開始并希望將其保存為 JSON 時才有意義。您的檔案只有完整的 JSON 文本,因此基本上將每一行按原樣復制粘貼到新檔案中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/394341.html
