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 __author__ = "Vratko Polak"
9 __copyright__ = "Copyright(c) 2015, Cisco Systems, Inc."
10 __license__ = "Eclipse Public License v1.0"
11 __email__ = "vrpolak@cisco.com"
14 import simplejson as _json
15 except ImportError: # Python2.7 calls it json.
17 from hsfl import Hsfl as _Hsfl
18 from hsfod import Hsfod as _Hsfod
21 def _hsfl_array(s_and_end, scan_once, **kwargs):
22 """Scan JSON array as usual, but return hsfl instead of list."""
23 values, end = _json.decoder.JSONArray(s_and_end, scan_once, **kwargs)
24 return _Hsfl(values), end
27 class _Decoder(_json.JSONDecoder):
28 """Private class to act as customized JSON decoder.
30 Based on: http://stackoverflow.com/questions/10885238/
31 python-change-list-type-for-json-decoding"""
32 def __init__(self, **kwargs):
33 """Initialize decoder with special array implementation."""
34 _json.JSONDecoder.__init__(self, **kwargs)
35 # Use the custom JSONArray
36 self.parse_array = _hsfl_array
37 # Use the python implemenation of the scanner
38 self.scan_once = _json.scanner.py_make_scanner(self)
41 def hsf_json(text): # pylint likes lowercase, Robot shall understand Hsf_Json
42 """Return sorted indented JSON string, or an error message string."""
44 object_decoded = _json.loads(text, cls=_Decoder, object_hook=_Hsfod)
45 except ValueError as err:
46 return str(err) + '\n' + text
47 pretty_json = _json.dumps(object_decoded, separators=(',', ': '), indent=1)
48 return pretty_json + '\n' # to avoid diff "no newline" warning line