แปลงจาก .json เป็น .csv ด้วย Python 3.8

แปลงด้วย Pandas

ติดตั้ง Pandas

python -m pip install pandas

แปลงจาก .json เป็น .csv ด้วย Pandas

import pandas as pd
df = pd.read_json (r'test.json')
df.to_csv (r'test.csv', index = None)

แปลงด้วย csv, json

import csv, json
fileInput = r'test.json'
fileOutput = r'test.csv'
inputFile = open(fileInput, 'r', encoding='utf-8') #open json file
outputFile = open(fileOutput, 'w', encoding='utf-8') #load csv file
data = json.load(inputFile) #load json content
inputFile.close() #close the input file
output = csv.writer(outputFile) #create a csv.write
output.writerow(data[0].keys())  # header row
f = True
for row in data:
    output.writerow(row.values()) #values row

แต่บางทีจะมีบรรทัดวางเกินมา ก็ลบบรรทัดว่างทิ้ง

filename_ip = 'test.csv'
filename_op = 'test.csv'
file = open(filename_ip, 'r', encoding='utf-8')
text = file.read()
lines = text.split('\n')
new_text = ''
for i in range(0, len(lines)):
    if (lines[i]!=''):
        new_text += lines[i] + '\n'
f = open(filename_op, 'w', encoding='utf-8')
f.write(new_text)
f.close()

ส่วนวิธีนี้ยังไม่ได้ลอง Convert JSON to CSV in Python – GeeksforGeeks