使用python创建Json表的最佳方法是什么?

时间:2019-06-26 11:48:09

标签: python json datatable

我正在从sql数据库中提取数据,并希望将该数据存储为json表。目前,我将其输出为csv,以便能够在excel中轻松可视化数据。我理解一切,减去如何格式化和使用json文件。

1 个答案:

答案 0 :(得分:1)

将CSV转换为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)
for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write('\n')

OR

更可行的解决方案

import pandas as pd

df = pd.read_csv('final_coupa.csv')
df['json'] = df.apply(lambda x: x.to_json(), axis=1)

df['json'].to_csv('final_json', index=False)

希望这会有所帮助。

相关问题