def command_encode(ns): """ Command to encode given JSON file from command line into BUFR file. """ encoder = Encoder( definitions_dir=ns.definitions_directory, tables_root_dir=ns.tables_root_directory, compiled_template_cache_max=ns.compiled_template_cache_max, master_table_version=ns.master_table_version) if ns.filename != '-': with open(ns.filename) as ins: s = ins.read() else: # read from stdin, this is useful for piping s = sys.stdin.read() messages = { (True, True): 'Nested JSON', (True, False): 'Nested Text', (False, True): 'Flat JSON', (False, False): 'Flat Text', } try: if ns.json: data = json.loads(s) if ns.attributed: data = nested_json_to_flat_json(data) else: if ns.attributed: data = nested_text_to_flat_json(s) else: data = flat_text_to_flat_json(s) except (ValueError, SyntaxError): raise PyBufrKitError('Invalid input: Is it in {} format?'.format( messages[(ns.attributed, ns.json)])) bufr_message = encoder.process(data, '<stdin>' if ns.filename else ns.filename, wire_template_data=False) if ns.output_filename: fmode = 'ab' if ns.append else 'wb' with open(ns.output_filename, fmode) as outs: if ns.preamble: outs.write(str.encode(ns.preamble, encoding='utf8')) outs.write(bufr_message.serialized_bytes)
def func(filename): s = read_bufr_file(filename) bufr_message = decoder.process(s) nested = nested_json_renderer.render(bufr_message) flat = flat_json_renderer.render(bufr_message) assert flat == nested_json_to_flat_json(nested)