From c2224e4fa466ba8372e2f5898fc299b8923c6c73 Mon Sep 17 00:00:00 2001 From: Martin Levy Date: Sun, 25 Feb 2018 02:09:58 -0800 Subject: [PATCH] NDJSON output supported - used by Enterprise Logs --- cli4/cli4.man | 3 +++ cli4/cli4.py | 18 ++++++++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/cli4/cli4.man b/cli4/cli4.man index 89c85c9..de18d1c 100644 --- a/cli4/cli4.man +++ b/cli4/cli4.man @@ -11,6 +11,7 @@ cli4 \- Command line access to CloudFlare v4 API [\fB\-q\fR|\fB\-\-quiet] [\fB\-j\fR|\fB\-\-json] [\fB\-y\fR|\fB\-\-yaml] +[\fB\-n\fR|\fB\-\-ndjson] [\fBitem\fR=\fIvalue\fR ...] [\fB\-G\fR|\fB\-\-get] [\fB\-P\fR|\fB\-\-patch] @@ -37,6 +38,8 @@ Don't output any JSON/YAML responses. Output response data in JSON format (the default). .IP "[\-y, \-\-yaml]" Output response data in YAML format (if yaml package installed). +.IP "[\-n, \-\-ndjson]" +Output response data in NDJSON format (if jsonlines package installed). .IP "\-\-get" Send HTTP request as a \fBGET\fR (the default). .IP "\-\-patch" diff --git a/cli4/cli4.py b/cli4/cli4.py index 0973868..dfae2cf 100644 --- a/cli4/cli4.py +++ b/cli4/cli4.py @@ -9,6 +9,10 @@ import yaml except ImportError: yaml = None +try: + import jsonlines +except ImportError: + jsonlines = None from . import converters @@ -185,6 +189,12 @@ def write_results(results, output): ensure_ascii=False) if output == 'yaml': results = yaml.safe_dump(results) + if output == 'ndjson': + # NDJSON support seems like a hack. There has to be a better way + writer = jsonlines.Writer(sys.stdout) + writer.write_all(results) + writer.close() + return sys.stdout.write(results) if not results.endswith('\n'): @@ -200,7 +210,7 @@ def do_it(args): method = 'GET' usage = ('usage: cli4 ' - + '[-V|--version] [-h|--help] [-v|--verbose] [-q|--quiet] [-j|--json] [-y|--yaml] ' + + '[-V|--version] [-h|--help] [-v|--verbose] [-q|--quiet] [-j|--json] [-y|--yaml] [-n|ndjson]' + '[-r|--raw] ' + '[-d|--dump] ' + '[--get|--patch|--post|--put|--delete] ' @@ -212,7 +222,7 @@ def do_it(args): 'VhvqjyrdGPOUD', [ 'version', - 'help', 'verbose', 'quiet', 'json', 'yaml', + 'help', 'verbose', 'quiet', 'json', 'yaml', 'ndjson', 'raw', 'dump', 'get', 'patch', 'post', 'put', 'delete' @@ -234,6 +244,10 @@ def do_it(args): if yaml is None: exit('cli4: install yaml support') output = 'yaml' + elif opt in ('-n', '--ndjson'): + if jsonlines is None: + exit('cli4: install jsonlines support') + output = 'ndjson' elif opt in ('-r', '--raw'): raw = True elif opt in ('-d', '--dump'):