summaryrefslogtreecommitdiff
path: root/cliff/formatters
diff options
context:
space:
mode:
authorSteve Baker <sbaker@redhat.com>2015-08-17 15:29:29 +1200
committerSteve Baker <sbaker@redhat.com>2015-08-18 09:42:19 +1200
commit4e1470d93e101d1390b39b93dec569c7c8966b83 (patch)
tree0babb9f1ef5a085f33d1aa56e1d725e17c776e4a /cliff/formatters
parent0a8daff7bdad7c56bc7b9dc2d6dea6b7259d2827 (diff)
downloadcliff-4e1470d93e101d1390b39b93dec569c7c8966b83.tar.gz
Implement a json formatter in cliff
This change replaces the cliff-tablib json formatter with an internal replacement. It differs from the tablib formatter in the following ways: - by default outputs with an indent of 2 spaces. The --noindent formatting argument outputs with no indentation, to save space or to pipe to tools which can't handle multi-line input. - emit_one serialises a simple dict where the column name is the key and the data item is the value (rather than a list of dicts with 'Field' and 'Value' keys) The cliff release which contains this change will need a corresponding cliff-tablib release which removes the json formatter from its setup.py entry_points. Change-Id: I7f9b1f339d96ead347a0c9d95ec7004a78d8c9d5 Related-Bug: #1308744
Diffstat (limited to 'cliff/formatters')
-rw-r--r--cliff/formatters/json_format.py30
1 files changed, 30 insertions, 0 deletions
diff --git a/cliff/formatters/json_format.py b/cliff/formatters/json_format.py
new file mode 100644
index 0000000..fc35da1
--- /dev/null
+++ b/cliff/formatters/json_format.py
@@ -0,0 +1,30 @@
+"""Output formatters for JSON.
+"""
+
+import json
+
+from .base import ListFormatter, SingleFormatter
+
+
+class JSONFormatter(ListFormatter, SingleFormatter):
+
+ def add_argument_group(self, parser):
+ group = parser.add_argument_group(title='json formatter')
+ group.add_argument(
+ '--noindent',
+ action='store_true',
+ dest='noindent',
+ help='whether to disable indenting the JSON'
+ )
+
+ def emit_list(self, column_names, data, stdout, parsed_args):
+ items = []
+ for item in data:
+ items.append(dict(zip(column_names, item)))
+ indent = None if parsed_args.noindent else 2
+ json.dump(items, stdout, indent=indent)
+
+ def emit_one(self, column_names, data, stdout, parsed_args):
+ one = dict(zip(column_names, data))
+ indent = None if parsed_args.noindent else 2
+ json.dump(one, stdout, indent=indent)