How to convert a QTable to JSON

Hi all!

I’m trying to convert a QTable to a json object thorugh this function. I have this error TypeError: Object of type Time is not JSON serializable.
I think I must convert the Date column to some iso format, but I don’t know how.

Any help?

You don’t say if your Time is an Time is an astropy Time object or a Python datetime. I’m assuming the former, since you pasted this under astropy, but if not the same idea applies:

The time object internally has all sorts of metadata (e.g. the format for output for string) and does not know how to put that into json. So, it needs a little help. You can manually convert your time into a format that’s easier to save a json, e.g. an ISO time as a string or as a number in JD. What format is best for you depends on your application, so I’m just giving one example, see the astropy docs for more formats that a time or date can converted to.

import json
import numpy as np
from astropy.time import Time
from astropy.table import QTable
import astropy.units as u

times = ['1999-01-01T00:00:00.123456789', '2010-01-01T00:00:00']
t = Time(times, format='isot', scale='utc')

tab = QTable({'date': t, 'mag': [15, 15.6] * u.mag})
json.dumps({'date': tab['date'].jd.tolist(), 
            'mag': tab['mag'].value.tolist()})

However, note that you get all the numbers, but loose the metadata (e.g. the units) from your table. Depending on what you need the json for, that might be OK, but in other cases, a lossless format could be more useful, e.g. tab.write('filename.ecsv').