SNABSuite  0.x
Spiking Neural Architecture Benchmark Suite
autoformat_json.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 
4 # SNABSuite -- Spiking Neural Architecture Benchmark Suite
5 # Copyright (C) 2019 Christoph Ostrau
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>
19 
20 """
21 Plots data from one dimensional sweeps
22 """
23 from builtins import range
24 import argparse
25 import json
26 import glob
27 import numpy
28 
29 parser = argparse.ArgumentParser(description='Autoformat json files in a folder')
30 
31 # Required Parameters
32 parser.add_argument("files", metavar="files", type=str, help="path to folder")
33 args = parser.parse_args()
34 
35 list_files = glob.glob(args.files + "*.json")
36 
37 # Adapted from https://stackoverflow.com/questions/21866774/pretty-print-json-dumps
38 INDENT = 4
39 SPACE = " "
40 NEWLINE = "\n"
41 
42 def to_json(o, level=0):
43  ret = ""
44  if isinstance(o, dict):
45  ret += "{" + NEWLINE
46  comma = ""
47  for k,v in o.items():
48  ret += comma
49  comma = ",\n"
50  ret += SPACE * INDENT * (level+1)
51  ret += '"' + str(k) + '":' + SPACE
52  ret += to_json(v, level + 1)
53 
54  ret += NEWLINE + SPACE * INDENT * level + "}"
55  elif isinstance(o, str):
56  ret += '"' + o + '"'
57  elif isinstance(o, list):
58  ret += "[" + ",".join([to_json(e, level+1) for e in o]) + "]"
59  elif isinstance(o, bool):
60  ret += "true" if o else "false"
61  elif isinstance(o, int):
62  ret += str(o)
63  elif isinstance(o, float):
64  ret += '%.7g' % o
65  elif isinstance(o, numpy.ndarray) and numpy.issubdtype(o.dtype, numpy.integer):
66  ret += "[" + ','.join(map(str, o.flatten().tolist())) + "]"
67  elif isinstance(o, numpy.ndarray) and numpy.issubdtype(o.dtype, numpy.inexact):
68  ret += "[" + ','.join(map(lambda x: '%.7g' % x, o.flatten().tolist())) + "]"
69  else:
70  raise TypeError("Unknown type '%s' for json serialization" % str(type(o)))
71  return ret
72 
73 def prettyfy(filename):
74  with open(filename) as file:
75  data = json.load(file)
76  with open(filename, 'w') as file:
77  file.write(to_json(data))
78 
79 for i in list_files:
80  print(i)
81  prettyfy(i)
def to_json(o, level=0)
def prettyfy(filename)