Debian Codegraph @

petl/io/json.py

raw
1 # -*- coding: utf-8 -*-
2 from __future__ import absolute_import, print_function, division
3
4 # standard library dependencies
5 import io
6 import json
7 import inspect
8 from json.encoder import JSONEncoder
9 from os import unlink
10 from tempfile import NamedTemporaryFile
11
12 from petl.compat import PY2
13 from petl.compat import pickle
14 from petl.io.sources import read_source_from_arg, write_source_from_arg
15 # internal dependencies
16 from petl.util.base import data, Table, dicts as _dicts, iterpeek
17
18
19 def fromjson(source, *args, **kwargs):
20 """
21 Extract data from a JSON file. The file must contain a JSON array as
22 the top level object, and each member of the array will be treated as a
23 row of data. E.g.::
24
25 >>> import petl as etl
26 >>> data = '''
27 ... [{"foo": "a", "bar": 1},
28 ... {"foo": "b", "bar": 2},
29 ... {"foo": "c", "bar": 2}]
30 ... '''
31 >>> with open('example.file1.json', 'w') as f:
32 ... f.write(data)
33 ...
34 74
35 >>> table1 = etl.fromjson('example.file1.json', header=['foo', 'bar'])
36 >>> table1
37 +-----+-----+
38 | foo | bar |
39 +=====+=====+
40 | 'a' | 1 |
41 +-----+-----+
42 | 'b' | 2 |
43 +-----+-----+
44 | 'c' | 2 |
45 +-----+-----+
46
47 Setting argument `lines` to `True` will enable to
48 infer the document as a JSON lines document. For more details about JSON lines
49 please visit https://jsonlines.org/.
50
51 >>> import petl as etl
52 >>> data_with_jlines = '''{"name": "Gilbert", "wins": [["straight", "7S"], ["one pair", "10H"]]}
53 ... {"name": "Alexa", "wins": [["two pair", "4S"], ["two pair", "9S"]]}
54 ... {"name": "May", "wins": []}
55 ... {"name": "Deloise", "wins": [["three of a kind", "5S"]]}'''
56 ...
57 >>> with open('example.file2.json', 'w') as f:
58 ... f.write(data_with_jlines)
59 ...
60 223
61 >>> table2 = etl.fromjson('example.file2.json', lines=True)
62 >>> table2
63 +-----------+-------------------------------------------+
64 | name | wins |
65 +===========+===========================================+
66 | 'Gilbert' | [['straight', '7S'], ['one pair', '10H']] |
67 +-----------+-------------------------------------------+
68 | 'Alexa' | [['two pair', '4S'], ['two pair', '9S']] |
69 +-----------+-------------------------------------------+
70 | 'May' | [] |
71 +-----------+-------------------------------------------+
72 | 'Deloise' | [['three of a kind', '5S']] |
73 +-----------+-------------------------------------------+
74
75 If your JSON file does not fit this structure, you will need to parse it
76 via :func:`json.load` and select the array to treat as the data, see also
77 :func:`petl.io.json.fromdicts`.
78
79 .. versionchanged:: 1.1.0
80
81 If no `header` is specified, fields will be discovered by sampling keys
82 from the first `sample` objects in `source`. The header will be
83 constructed from keys in the order discovered. Note that this
84 ordering may not be stable, and therefore it may be advisable to specify
85 an explicit `header` or to use another function like
86 :func:`petl.transform.headers.sortheader` on the resulting table to
87 guarantee stability.
88
89 """
90
91 source = read_source_from_arg(source)
92 return JsonView(source, *args, **kwargs)
93
94
95 class JsonView(Table):
96 def __init__(self, source, *args, **kwargs):
97 self.source = source
98 self.missing = kwargs.pop('missing', None)
99 self.header = kwargs.pop('header', None)
100 self.sample = kwargs.pop('sample', 1000)
101 self.lines = kwargs.pop('lines', False)
102 self.args = args
103 self.kwargs = kwargs
104
105 def __iter__(self):
106 with self.source.open('rb') as f:
107 if not PY2:
108 # wrap buffer for text IO
109 f = io.TextIOWrapper(f, encoding='utf-8', newline='',
110 write_through=True)
111 try:
112 if self.lines:
113 for row in iterjlines(f, self.header, self.missing):
114 yield row
115 else:
116 dicts = json.load(f, *self.args, **self.kwargs)
117 for row in iterdicts(dicts, self.header, self.sample,
118 self.missing):
119 yield row
120 finally:
121 if not PY2:
122 f.detach()
123
124
125 def fromdicts(dicts, header=None, sample=1000, missing=None):
126 """
127 View a sequence of Python :class:`dict` as a table. E.g.::
128
129 >>> import petl as etl
130 >>> dicts = [{"foo": "a", "bar": 1},
131 ... {"foo": "b", "bar": 2},
132 ... {"foo": "c", "bar": 2}]
133 >>> table1 = etl.fromdicts(dicts, header=['foo', 'bar'])
134 >>> table1
135 +-----+-----+
136 | foo | bar |
137 +=====+=====+
138 | 'a' | 1 |
139 +-----+-----+
140 | 'b' | 2 |
141 +-----+-----+
142 | 'c' | 2 |
143 +-----+-----+
144
145 Argument `dicts` can also be a generator, the output of generator
146 is iterated and cached using a temporary file to support further
147 transforms and multiple passes of the table:
148
149 >>> import petl as etl
150 >>> dicts = ({"foo": chr(ord("a")+i), "bar":i+1} for i in range(3))
151 >>> table1 = etl.fromdicts(dicts, header=['foo', 'bar'])
152 >>> table1
153 +-----+-----+
154 | foo | bar |
155 +=====+=====+
156 | 'a' | 1 |
157 +-----+-----+
158 | 'b' | 2 |
159 +-----+-----+
160 | 'c' | 3 |
161 +-----+-----+
162
163 If `header` is not specified, `sample` items from `dicts` will be
164 inspected to discovery dictionary keys. Note that the order in which
165 dictionary keys are discovered may not be stable,
166
167 See also :func:`petl.io.json.fromjson`.
168
169 .. versionchanged:: 1.1.0
170
171 If no `header` is specified, fields will be discovered by sampling keys
172 from the first `sample` dictionaries in `dicts`. The header will be
173 constructed from keys in the order discovered. Note that this
174 ordering may not be stable, and therefore it may be advisable to specify
175 an explicit `header` or to use another function like
176 :func:`petl.transform.headers.sortheader` on the resulting table to
177 guarantee stability.
178
179 .. versionchanged:: 1.7.5
180
181 Full support of generators passed as `dicts` has been added, leveraging
182 `itertools.tee`.
183
184 .. versionchanged:: 1.7.11
185
186 Generator support has been modified to use temporary file cache
187 instead of `itertools.tee` due to high memory usage.
188
189 """
190 view = DictsGeneratorView if inspect.isgenerator(dicts) else DictsView
191 return view(dicts, header=header, sample=sample, missing=missing)
192
193
194 class DictsView(Table):
195
196 def __init__(self, dicts, header=None, sample=1000, missing=None):
197 self.dicts = dicts
198 self._header = header
199 self.sample = sample
200 self.missing = missing
201
202 def __iter__(self):
203 return iterdicts(self.dicts, self._header, self.sample, self.missing)
204
205
206 class DictsGeneratorView(DictsView):
207
208 def __init__(self, dicts, header=None, sample=1000, missing=None):
209 super(DictsGeneratorView, self).__init__(dicts, header, sample, missing)
210 self._filecache = None
211 self._cached = 0
212
213 def __iter__(self):
214 if not self._header:
215 self._determine_header()
216 yield self._header
217
218 if not self._filecache:
219 if PY2:
220 self._filecache = NamedTemporaryFile(delete=False, mode='wb+', bufsize=0)
221 else:
222 self._filecache = NamedTemporaryFile(delete=False, mode='wb+', buffering=0)
223
224 position = 0
225 it = iter(self.dicts)
226 while True:
227 if position < self._cached:
228 self._filecache.seek(position)
229 row = pickle.load(self._filecache)
230 position = self._filecache.tell()
231 yield row
232 continue
233 try:
234 o = next(it)
235 except StopIteration:
236 break
237 row = tuple(o.get(f, self.missing) for f in self._header)
238 self._filecache.seek(self._cached)
239 pickle.dump(row, self._filecache, protocol=-1)
240 self._cached = position = self._filecache.tell()
241 yield row
242
243 def _determine_header(self):
244 it = iter(self.dicts)
245 header = list()
246 peek, it = iterpeek(it, self.sample)
247 self.dicts = it
248 if isinstance(peek, dict):
249 peek = [peek]
250 for o in peek:
251 if hasattr(o, 'keys'):
252 header += [k for k in o.keys() if k not in header]
253 self._header = tuple(header)
254 return it
255
256 def __del__(self):
257 if self._filecache:
258 self._filecache.close()
259 unlink(self._filecache.name)
260
261
262 def iterjlines(f, header, missing):
263 it = iter(f)
264
265 if header is None:
266 header = list()
267 peek, it = iterpeek(it, 1)
268 json_obj = json.loads(peek)
269 if hasattr(json_obj, 'keys'):
270 header += [k for k in json_obj.keys() if k not in header]
271 yield tuple(header)
272
273 for o in it:
274 json_obj = json.loads(o)
275 yield tuple(json_obj[f] if f in json_obj else missing for f in header)
276
277
278 def iterdicts(dicts, header, sample, missing):
279 it = iter(dicts)
280
281 # determine header row
282 if header is None:
283 # discover fields
284 header = list()
285 peek, it = iterpeek(it, sample)
286 for o in peek:
287 if hasattr(o, 'keys'):
288 header += [k for k in o.keys() if k not in header]
289 yield tuple(header)
290
291 # generate data rows
292 for o in it:
293 yield tuple(o.get(f, missing) for f in header)
294
295
296 def tojson(table, source=None, prefix=None, suffix=None, *args, **kwargs):
297 """
298 Write a table in JSON format, with rows output as JSON objects. E.g.::
299
300 >>> import petl as etl
301 >>> table1 = [['foo', 'bar'],
302 ... ['a', 1],
303 ... ['b', 2],
304 ... ['c', 2]]
305 >>> etl.tojson(table1, 'example.file3.json', sort_keys=True)
306 >>> # check what it did
307 ... print(open('example.file3.json').read())
308 [{"bar": 1, "foo": "a"}, {"bar": 2, "foo": "b"}, {"bar": 2, "foo": "c"}]
309
310
311
312 Setting argument `lines` to `True` will enable to
313 infer the writing format as a JSON lines . For more details about JSON lines
314 please visit https://jsonlines.org/.
315
316 >>> import petl as etl
317 >>> table1 = [['name', 'wins'],
318 ... ['Gilbert', [['straight', '7S'], ['one pair', '10H']]],
319 ... ['Alexa', [['two pair', '4S'], ['two pair', '9S']]],
320 ... ['May', []],
321 ... ['Deloise',[['three of a kind', '5S']]]]
322 >>> etl.tojson(table1, 'example.file3.jsonl', lines = True, sort_keys=True)
323 >>> # check what it did
324 ... print(open('example.file3.jsonl').read())
325 {"name": "Gilbert", "wins": [["straight", "7S"], ["one pair", "10H"]]}
326 {"name": "Alexa", "wins": [["two pair", "4S"], ["two pair", "9S"]]}
327 {"name": "May", "wins": []}
328 {"name": "Deloise", "wins": [["three of a kind", "5S"]]}
329
330 Note that this is currently not streaming, all data is loaded into memory
331 before being written to the file.
332
333 """
334
335 obj = [row for row in _dicts(table)]
336 _writejson(source, obj, prefix, suffix, *args, **kwargs)
337
338
339 Table.tojson = tojson
340
341
342 def tojsonarrays(table, source=None, prefix=None, suffix=None,
343 output_header=False, *args, **kwargs):
344 """
345 Write a table in JSON format, with rows output as JSON arrays. E.g.::
346
347 >>> import petl as etl
348 >>> table1 = [['foo', 'bar'],
349 ... ['a', 1],
350 ... ['b', 2],
351 ... ['c', 2]]
352 >>> etl.tojsonarrays(table1, 'example.file4.json')
353 >>> # check what it did
354 ... print(open('example.file4.json').read())
355 [["a", 1], ["b", 2], ["c", 2]]
356
357 Note that this is currently not streaming, all data is loaded into memory
358 before being written to the file.
359
360 """
361
362 if output_header:
363 obj = [row for row in table]
364 else:
365 obj = [row for row in data(table)]
366 _writejson(source, obj, prefix, suffix, *args, **kwargs)
367
368
369 Table.tojsonarrays = tojsonarrays
370
371
372 def _writejson(source, obj, prefix, suffix, *args, **kwargs):
373 lines = kwargs.pop('lines', False)
374 encoder = JSONEncoder(*args, **kwargs)
375 source = write_source_from_arg(source)
376 with source.open('wb') as f:
377 if PY2:
378 # write directly to buffer
379 _writeobj(encoder, obj, f, prefix, suffix, lines=lines)
380 else:
381 # wrap buffer for text IO
382 f = io.TextIOWrapper(f, encoding='utf-8', newline='',
383 write_through=True)
384 try:
385 _writeobj(encoder, obj, f, prefix, suffix, lines=lines)
386 finally:
387 f.detach()
388
389
390 def _writeobj(encoder, obj, f, prefix, suffix, lines=False):
391 if prefix is not None:
392 f.write(prefix)
393 if lines:
394 for rec in obj:
395 for chunk in encoder.iterencode(rec):
396 f.write(chunk)
397 f.write('\n')
398 else:
399 for chunk in encoder.iterencode(obj):
400 f.write(chunk)
401 if suffix is not None:
402 f.write(suffix)