數據處理-csv文件轉化爲json

import csv,json
import pandas as pd

"""
奴隸社會,非洲,
奴隸社會,亞洲,
奴隸社會,亞洲,古印度
奴隸社會,歐洲,

"""

def csv2json(file_path):
    with open(file_path,"r",encoding='UTF-8') as f:
        reader = csv.reader(f,dialect='excel')
        obj = {}
        t1=t2=t3=""
        for row in reader:
            d1,d2,d3 = row[0],row[1],row[2]
            if d1!="":
                t1 = d1
                obj[t1] = []
            if d2!="":
                t2 = d2
                obj[t1].append({t2:[]})
            if d3!="":
                t3 = d3
                obj[t1][-1][t2].append({t3:[]})

        return obj

print(csv2json("./history.csv"))

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章