From 2cc992a8bc19126f4ca27aedea3b1591fa59710f Mon Sep 17 00:00:00 2001 From: Romain Bignon Date: Fri, 23 Sep 2011 10:00:46 +0200 Subject: [PATCH] new parser 'json' --- weboob/tools/parsers/__init__.py | 6 +++++ weboob/tools/parsers/jsonparser.py | 41 ++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 weboob/tools/parsers/jsonparser.py diff --git a/weboob/tools/parsers/__init__.py b/weboob/tools/parsers/__init__.py index e056c696..44ac4c27 100644 --- a/weboob/tools/parsers/__init__.py +++ b/weboob/tools/parsers/__init__.py @@ -46,6 +46,12 @@ def load_builtin(): from .htmlparser import HTMLParser return HTMLParser +def load_json(): + # This parser doesn't read HTML, don't include it in the + # preference_order default value below. + from .jsonparser import JsonParser + return JsonParser + def get_parser(preference_order=('lxml', 'lxmlsoup', 'html5lib', 'elementtidy', 'builtin')): """ Get a parser from a preference order list. diff --git a/weboob/tools/parsers/jsonparser.py b/weboob/tools/parsers/jsonparser.py new file mode 100644 index 00000000..29d6fcc8 --- /dev/null +++ b/weboob/tools/parsers/jsonparser.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- + +# Copyright(C) 2011 Romain Bignon +# +# This file is part of weboob. +# +# weboob is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# weboob is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with weboob. If not, see . + + +try: + import json +except ImportError: + import simplejson as json + +from .iparser import IParser + + +__all__ = ['JsonParser'] + + +class JsonParser(IParser): + """ + Json parser. + """ + + def parse(self, data, encoding=None): + return json.load(data, encoding=encoding) + + def tostring(self, element): + return json.dumps(element)