简体   繁体   中英

Convert sql table to json

I am trying to fetch data from mysql server, and to save it as json.

BUT somehow when transforming to json, date format gets lost. Look at start & end in data and output.

Making connection:

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)

data i get looks like:

   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

then i used pandas to create json file

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

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

the file output

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

use parameter 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"}]'

from Pandas docs :

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

Type of date conversion. epoch = epoch milliseconds, 'iso' = ISO8601.

The default depends on the orient .

For orient='table' , the default is 'iso' .

For all other orients, the default is 'epoch' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM