comparison configmix/json.py @ 127:5b62d2c0e5a8

Use the available "OrderedDict" class as dict for the JSON parser
author Franz Glasner <hg@dom66.de>
date Wed, 04 Apr 2018 20:53:06 +0200
parents be6cdc9cb79c
children 95ad65c69561
comparison
equal deleted inserted replaced
126:93964bac7ef6 127:5b62d2c0e5a8
9 9
10 from __future__ import division, absolute_import, print_function 10 from __future__ import division, absolute_import, print_function
11 11
12 import io 12 import io
13 import json.decoder 13 import json.decoder
14 try:
15 from collections import OrderedDict as DictImpl
16 except ImportError:
17 try:
18 from ordereddict import OrderedDict as DictImpl
19 except ImportError:
20 DictImpl = dict
14 21
15 22
16 __all__ = ["load"] 23 __all__ = ["load"]
24
25
26 #
27 # Determine whether the JSONDecoder has the "object_pairs_hook"
28 # parameter once
29 #
30 try:
31 json.decoder.JSONDecoder(object_pairs_hook=DictImpl)
32 except TypeError:
33 _with_object_pairs_hook = False
34 else:
35 _with_object_pairs_hook = True
17 36
18 37
19 def load(filename, encoding="utf-8"): 38 def load(filename, encoding="utf-8"):
20 """Load a single JSON file with name `filename` and encoding `encoding`. 39 """Load a single JSON file with name `filename` and encoding `encoding`.
21 40
22 .. todo:: Allow comments in JSON files 41 .. todo:: Allow comments in JSON files
23 42
24 .. todo:: Allow all Python string literals 43 .. todo:: Allow all Python string literals
25 44
26 .. todo:: Use OrderedDict as default mapping implementation (Python 2.7+)
27
28 """ 45 """
29 with io.open(filename, mode="rt", encoding=encoding) as jsfp: 46 with io.open(filename, mode="rt", encoding=encoding) as jsfp:
30 decoder = json.decoder.JSONDecoder( 47 kwds = {
31 parse_int=lambda n: int(n, 0), 48 "parse_int": lambda n: int(n, 0),
32 strict=False) 49 "strict": False
50 }
51 if _with_object_pairs_hook:
52 kwds["object_pairs_hook"] = DictImpl
53 decoder = json.decoder.JSONDecoder(**kwds)
33 return decoder.decode(jsfp.read()) 54 return decoder.decode(jsfp.read())