dmrg_json_utils.py
1 """
2 @package dmrg_json_utils
3 @brief Python module for reading JSON data files produced by a DMRG.x application.
4 
5 @defgroup JSONUtilities JSON Utilities
6 @brief Python module for reading JSON data files produced by a DMRG.x application.
7 """
8 
9 
12 
13 import json
14 from shutil import copyfile
15 
16 def LoadJSONFile(path,appendStr,count=0):
17  """ Loads data from a JSON file and corrects unfinished runs by appending a
18  string to the file.
19 
20  Args:
21  path: path to json file
22  appendStr: string to append in case of a JSONDecodeError
23  count: number of times this function was called recursively
24 
25  Returns:
26  dict object representing the loaded data
27 
28  Raises:
29  Exception: Unable to correctly load the file with the appended string.
30 
31  Note:
32  For portability, this function detects a ValueError instead of a
33  JSONDecodeError which inherits from it.
34 
35  """
36  filemod = path[:-5]+"-mod"+".json"
37  try:
38  if count == 0:
39  data = json.load(open(path))
40  elif count == 1:
41  data = json.load(open(filemod))
42  else:
43  raise Exception('LoadJSONFile was not able to correct the file "{}" with an appended "{}". '
44  'Check the file manually.'.format(path,appendStr))
45  return data
46  except ValueError:
47  copyfile(path,filemod)
48  fh = open(filemod, "a")
49  fh.write(appendStr)
50  fh.close()
51  return LoadJSONFile(path,appendStr,count+1)
52 
53 def LoadJSONDict(path):
54  """ Loads data from a JSON file containing dict entries and corrects unfinished
55  runs by appending "}".
56 
57  Args:
58  path: path to json file
59 
60  """
61  return LoadJSONFile(path,"}")
62 
63 def LoadJSONTable(path):
64  """Loads data from a JSON file with keys "headers" and "table", and corrects
65  unfinished runs by appending "]}".
66 
67  Args:
68  path: path to json file
69  """
70  return LoadJSONFile(path,"]}")
71 
72 def LoadJSONArray(path):
73  """Loads data from a JSON file represented as an array of dictionary entries
74  and corrects unfinished runs by appending "]".
75 
76  Args:
77  path: path to json file
78  """
79  return LoadJSONFile(path,"]")
80 
81 
def LoadJSONTable(path)
Loads data from a JSON file with keys "headers" and "table", and corrects unfinished runs by appendin...
def LoadJSONFile(path, appendStr, count=0)
Loads data from a JSON file and corrects unfinished runs by appending a string to the file...
def LoadJSONArray(path)
Loads data from a JSON file represented as an array of dictionary entries and corrects unfinished run...
def LoadJSONDict(path)
Loads data from a JSON file containing dict entries and corrects unfinished runs by appending "}"...
This site was generated by Sphinx using Doxygen with a customized theme from doxygen-bootstrapped.