jsonextended.ejson module

jsonextended.ejson.jkeys(jfile, key_path=None, in_memory=True, ignore_prefix=('.', '_'))[source]

get keys for initial json level, or at level after following key_path

Parameters:
  • jfile (str, file_like or path_like) – if str, must be existing file or folder, if file_like, must have ‘read’ method if path_like, must have ‘iterdir’ method (see pathlib.Path)
  • key_path (list[str]) – a list of keys to index into the json before returning keys
  • in_memory (bool) – if true reads json into memory before finding keys (this is faster but uses more memory)
  • ignore_prefix (list[str]) – ignore folders beginning with these prefixes

Examples

>>> from jsonextended.utils import MockPath
>>> file_obj = MockPath('test.json',is_file=True,
... content='''
... {
...  "a": 1,
...  "b": [1.1,2.1],
...  "c": {"d":"e","f":"g"}
... }
... ''')
...
>>> jkeys(file_obj)
['a', 'b', 'c']
>>> jkeys(file_obj,["c"])
['d', 'f']
>>> from jsonextended.utils import get_test_path
>>> path = get_test_path()
>>> jkeys(path)
['dir1', 'dir2', 'dir3']
>>> path = get_test_path()
>>> jkeys(path, ['dir1','file1'], in_memory=True)
['initial', 'meta', 'optimised', 'units']
jsonextended.ejson.to_dict(jfile, key_path=None, in_memory=True, ignore_prefix=('.', '_'), parse_decimal=False)[source]

input json to dict

Parameters:
  • jfile (str, file_like or path_like) – if str, must be existing file or folder, if file_like, must have ‘read’ method if path_like, must have ‘iterdir’ method (see pathlib.Path)
  • key_path (list[str]) – a list of keys to index into the json before parsing it
  • in_memory (bool) – if true reads full json into memory before filtering keys (this is faster but uses more memory)
  • ignore_prefix (list[str]) – ignore folders beginning with these prefixes
  • parse_decimal (bool) – whether to parse numbers as Decimal instances (retains exact precision)

Examples

>>> from pprint import pformat
>>> from jsonextended.utils import MockPath
>>> file_obj = MockPath('test.json',is_file=True,
... content='''
... {
...  "a": 1,
...  "b": [1.1,2.1],
...  "c": {"d":"e"}
... }
... ''')
...
>>> dstr = pformat(to_dict(file_obj))
>>> print(dstr.replace("u'","'"))
{'a': 1, 'b': [1.1, 2.1], 'c': {'d': 'e'}}
>>> dstr = pformat(to_dict(file_obj,parse_decimal=True))
>>> print(dstr.replace("u'","'"))
{'a': 1, 'b': [Decimal('1.1'), Decimal('2.1')], 'c': {'d': 'e'}}
>>> str(to_dict(file_obj,["c","d"]))
'e'
>>> from jsonextended.utils import get_test_path
>>> path = get_test_path()
>>> jdict1 = to_dict(path)
>>> pprint(jdict1,depth=2)
dir1:
  dir1_1: {...}
  file1: {...}
  file2: {...}
dir2:
  file1: {...}
dir3:
>>> jdict2 = to_dict(path,['dir1','file1','initial'],in_memory=False)
>>> pprint(jdict2,depth=1)
crystallographic: {...}
primitive: {...}