#!/usr/bin/python3 # The MIT License (MIT) # # Copyright © 2020-2025 pacman64 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the “Software”), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from json import load, dump from sys import argv, exit, stderr, stdin, stdout info = ''' jsonl [filepath/URI...] JSON Lines turns valid JSON-input arrays into separate JSON lines, one for each top-level item. Non-arrays result in a single JSON-line. When not given a filepath or URI to load, standard input is used instead. Every output line is always a single top-level item from the input. ''' # handle standard help cmd-line options, quitting right away in that case if len(argv) == 2 and argv[1] in ('-h', '--h', '-help', '--help'): print(info.strip()) exit(0) def jsonl(w, src) -> None: data = load(src) if isinstance(data, (list, tuple)): for v in data: emit(w, v) else: emit(w, data) def emit(w, v) -> None: dump(v, w, indent=None, allow_nan=False, separators=(', ', ': ')) w.write('\n') def seems_url(s: str) -> bool: protocols = ('https://', 'http://', 'file://', 'ftp://', 'data:') return any(s.startswith(p) for p in protocols) try: if len(argv) < 2: jsonl(stdout, stdin.buffer) elif len(argv) == 2: name = argv[1] if name == '-': jsonl(stdout, stdin.buffer) elif seems_url(name): from urllib.request import urlopen with urlopen(name) as inp: jsonl(stdout, inp) else: with open(name, mode='rb') as inp: jsonl(stdout, inp) else: raise ValueError('multiple inputs not allowed') except BrokenPipeError: # quit quietly, instead of showing a confusing error message stderr.close() exit(0) except KeyboardInterrupt: exit(2) except Exception as e: print(f'\x1b[31m{e}\x1b[0m', file=stderr) exit(1)