1# -*- coding: utf-8 -*- 2 3# Copyright(C) 2013-2014 Julien Hebert, Laurent Bachelier 4# 5# This file is part of weboob. 6# 7# weboob is free software: you can redistribute it and/or modify 8# it under the terms of the GNU Lesser General Public License as published by 9# the Free Software Foundation, either version 3 of the License, or 10# (at your option) any later version. 11# 12# weboob is distributed in the hope that it will be useful, 13# but WITHOUT ANY WARRANTY; without even the implied warranty of 14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15# GNU Lesser General Public License for more details. 16# 17# You should have received a copy of the GNU Lesser General Public License 18# along with weboob. If not, see <http://www.gnu.org/licenses/>. 19 20 21from weboob.tools.json import json, WeboobEncoder 22 23from .iformatter import IFormatter 24 25__all__ = ['JsonFormatter', 'JsonLineFormatter'] 26 27 28class JsonFormatter(IFormatter): 29 """ 30 Formats the whole list as a single JSON list object. 31 """ 32 33 def __init__(self): 34 super(JsonFormatter, self).__init__() 35 self.queue = [] 36 37 def flush(self): 38 self.output(json.dumps(self.queue, cls=WeboobEncoder)) 39 40 def format_dict(self, item): 41 self.queue.append(item) 42 43 def format_collection(self, collection, only): 44 self.queue.append(collection.to_dict()) 45 46 47class JsonLineFormatter(IFormatter): 48 """ 49 Formats the list as received, with a JSON object per line. 50 The advantage is that it can be streamed. 51 """ 52 53 def format_dict(self, item): 54 self.output(json.dumps(item, cls=WeboobEncoder)) 55 56 57def test(): 58 from .iformatter import formatter_test_output as fmt 59 assert fmt(JsonFormatter, {'foo': 'bar'}) == '[{"foo": "bar"}]\n' 60 assert fmt(JsonLineFormatter, {'foo': 'bar'}) == '{"foo": "bar"}\n' 61