将sql表转换为json

时间:2018-06-18 22:18:06

标签: python sql json pandas

我正在尝试从mysql服务器获取数据,并将其保存为json。

但是当转换为json时,日期格式会丢失。看看开始& 结束数据和输出。

建立联系:

import pandas as pd
import pymysql
from pandas import *


con='mysql+pymysql://username:password@host/table'

data=pd.read_sql_query('SELECT * FROM calendar_table',con)

数据我看起来像:

   id                title               start                 end  client
0   1  somethinginterestin 2018-06-21 12:00:00 2018-06-21 16:20:00    suja
1   2                vusce 2018-06-21 15:00:00 2018-06-22 08:00:00  vuscec

然后我用 pandas 创建了json文件

x = data.to_json(orient='records')

f = open("sqltable.json","w+")
f.write(x)
f.close()

文件输出

[{"id":1,"title":"somethinginterestin","start":1529582400000,"end":1529598000000,"client":"suja"},
{"id":2,"title":"vusce","start":1529593200000,"end":1529654400000,"client":"vuscec"}]

1 个答案:

答案 0 :(得分:0)

使用参数date_format='iso'

In [260]: df.to_json(orient='records', date_format='iso')
Out[260]: '[{"id":1,"title":"somethinginterestin","start":"2018-06-21T12:00:00.000Z","end":"2018-06-21T16:20:00.000Z","client":"suja"},{"id":2,"title":"vusce","
start":"2018-06-21T15:00:00.000Z","end":"2018-06-22T08:00:00.000Z","client":"vuscec"}]'

来自Pandas docs

  

date_format :{无,'epoch','iso'}

     

日期转换类型。 epoch =纪元毫秒,'iso' = ISO8601。

     

默认值取决于orient

     

对于orient='table',默认为'iso'

     

对于所有其他方面,      默认值为'epoch'