Debian Codegraph @

gavo/formats/jsontable.py

raw
1 """
2 Writing tables in JSON.
3
4 We use python's built-in json engine to write an -- as yet -- ad-hoc json
5 format that essentially looks like this::
6
7 {
8 "contains": "table",
9 "columns": { (column metadata more or less as in VOTable) }
10 "data": { (rows as tuples) }
11 ("warnings": [...])
12 }
13
14 No streaming at all is forseen for this format at this point.
15
16 Note that we don't do any custom type serialisers here; all the
17 stringification (or whatever) necessary happens within our own
18 mappers (utils.serializers or wherever something is added to the
19 defaultMFRegistry).
20 """
21
22 #c Copyright 2008-2025, the GAVO project <[email protected]>
23 #c
24 #c This program is free software, covered by the GNU GPL. See the
25 #c COPYING file in the source distribution.
26
27
28 import codecs
29 import json
30
31 from gavo import base
32 from gavo import rsc
33 from gavo.formats import common
34
35
36 class JSONMetaBuilder(base.MetaBuilder):
37 """A MetaBuilder for mapping table meta information into our standard
38 JSON structure.
39 """
40 def __init__(self, jsonStructure):
41 self.result = jsonStructure
42 base.MetaBuilder.__init__(self)
43
44 def getResult(self):
45 return self.result
46
47 def enterValue(self, value):
48 if self.curAtoms[-1]=="_warning":
49 self.result.setdefault("warnings", []).append(str(value))
50 elif self.curAtoms[-1]=="_queryStatus":
51 self.result["queryStatus"] = str(value)
52
53
54 def _getJSONColumns(serManager):
55 """returns a sequence of VOTable-like column description dictionaries.
56 """
57 res = []
58 for annCol in serManager:
59 res.append(annCol.annotations.copy())
60 res[-1].pop("displayHint", None)
61 res[-1].pop("winningFactory", None)
62 res[-1].pop("nullvalue", None)
63 res[-1].pop("note", None)
64 return res
65
66
67 def _getJSONParams(serManager):
68 """returns a dict of param dicts.
69 """
70 result = {
71 'contains': "params",
72 }
73 for param in serManager.table.iterParams():
74 if param.value is not None:
75 result[param.name] = {
76 'value': param.value,
77 'unit': param.unit,
78 'ucd': param.ucd,
79 'description': param.description,}
80 return result
81
82
83 def _getJSONStructure(table, acquireSamples=False):
84 """returns a dictionary representing table for JSON serialisation.
85 """
86 if isinstance(table, rsc.Data):
87 table = table.getPrimaryTable()
88 sm = base.SerManager(table, acquireSamples=acquireSamples)
89
90 result = {
91 'contains': "table",
92 'params': _getJSONParams(sm),
93 'columns': _getJSONColumns(sm),
94 'data': list(sm.getMappedTuples()),
95 }
96 table.traverse(JSONMetaBuilder(result))
97 return result
98
99
100 def writeTableAsJSON(table, target, acquireSamples=False):
101 """writes table to the target in ad-hoc JSON.
102 """
103 jsonPayload = _getJSONStructure(table, acquireSamples)
104 # our targets are always binary; wrap them for json.dump
105 target = codecs.getwriter("utf-8")(target)
106 return json.dump(jsonPayload, target)
107
108
109 # NOTE: while json could easily serialize full data elements,
110 # right now we're only writing single tables.
111 common.registerDataWriter("json", writeTableAsJSON, "application/json",
112 "JSON", ".json")