# Copyright 2022 Tomas Brabec # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pathlib import json import argparse import sys def json2huddle(data): if data is None: return None elif isinstance(data,str): return "s {" + data + "}" elif isinstance(data,(int,float)): return "n " + str(data) elif isinstance(data,bool): return "b " + str(data).lower() elif isinstance(data,list): l = [] for i in data: s = json2huddle(i) if s is None: l.append("null") else: l.append("{" + s + "}") return "L {" + " ".join(l) + "}" elif isinstance(data,dict): l = [] for k, v in data.items(): l.append(k) s = json2huddle(v) if s is None: l.append("null") else: l.append("{" + s + "}") return "D {" + " ".join(l) + "}" return "? {}" # Instantiate the parser parser = argparse.ArgumentParser(description='Optional app description') parser.add_argument('files', metavar='file', type=pathlib.Path, nargs='*', help='JSON files to validate') opts = parser.parse_args() if not opts.files: s = None data = json.load(sys.stdin) s = json2huddle(data) if s is None: s = "HUDDLE null" else: s = "HUDDLE (" + s + ")" print(s) else: for f in opts.files: p = pathlib.Path( f ) if p.is_file(): t = p.with_suffix('.huddle') print( str(t) ) s = None with open(f, 'r') as myfile: data=json.load(myfile) #print(json.dumps(data, indent=2)) #print("----") s = json2huddle(data) if s is None: s = "HUDDLE null" else: s = "HUDDLE {" + s + "}" print(s) if not s is None and not t.is_file(): with open(t, 'w') as myfile: myfile.write(s)