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