1 """This module contains single a function for normalizing JSON strings."""
2 # Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
4 # This program and the accompanying materials are made available under the
5 # terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 # and is available at http://www.eclipse.org/legal/epl-v10.html
8 # FIXME: Use ${CURDIR}/../norm_json.py everywhere, then delete ${CURDIR}.
9 # https://trello.com/c/N3s0xhc6/260-rename-hfsjson-hsf-json-py-to-something-friendlier
12 import simplejson as _json
13 except ImportError: # Python2.7 calls it json.
15 from hsfl import Hsfl as _Hsfl
16 from hsfod import Hsfod as _Hsfod
19 __author__ = "Vratko Polak"
20 __copyright__ = "Copyright(c) 2015, Cisco Systems, Inc."
21 __license__ = "Eclipse Public License v1.0"
22 __email__ = "vrpolak@cisco.com"
25 def _hsfl_array(s_and_end, scan_once, **kwargs):
26 """Scan JSON array as usual, but return hsfl instead of list."""
27 values, end = _json.decoder.JSONArray(s_and_end, scan_once, **kwargs)
28 return _Hsfl(values), end
31 class _Decoder(_json.JSONDecoder):
32 """Private class to act as customized JSON decoder.
34 Based on: http://stackoverflow.com/questions/10885238/
35 python-change-list-type-for-json-decoding"""
36 def __init__(self, **kwargs):
37 """Initialize decoder with special array implementation."""
38 _json.JSONDecoder.__init__(self, **kwargs)
39 # Use the custom JSONArray
40 self.parse_array = _hsfl_array
41 # Use the python implemenation of the scanner
42 self.scan_once = _json.scanner.py_make_scanner(self)
45 def hsf_json(text): # pylint likes lowercase, Robot shall understand Hsf_Json
46 """Return sorted indented JSON string, or an error message string."""
48 object_decoded = _json.loads(text, cls=_Decoder, object_hook=_Hsfod)
49 except ValueError as err:
50 return str(err) + '\n' + text
51 pretty_json = _json.dumps(object_decoded, separators=(',', ': '), indent=1)
52 return pretty_json + '\n' # to avoid diff "no newline" warning line