Skip to content

Commit 51e594b

Browse files
author
sharbov
committed
Fix json formatter
1 parent 9649a9d commit 51e594b

2 files changed

Lines changed: 21 additions & 6 deletions

File tree

open_cli/formatter.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
1+
import json
12
import tabulate
23

3-
from pprint import pformat
4-
5-
6-
def format_response(response, output_format):
7-
return u"\n{}\n".format(to_table(response) if output_format == "table" else pformat(response))
4+
JSON = "json"
5+
TABLE = "table"
86

97

108
def to_table(response):
@@ -27,3 +25,18 @@ def to_table(response):
2725
headers={key: key.capitalize() for key in response[0].keys()},
2826
tablefmt='grid'
2927
)
28+
29+
30+
def to_json(response):
31+
"""Convert raw response into json output."""
32+
return json.dumps(response, indent=2)
33+
34+
35+
FORMATTERS = {
36+
JSON: to_json,
37+
TABLE: to_table,
38+
}
39+
40+
41+
def format_response(response, output_format):
42+
return u"\n{}\n".format(FORMATTERS[output_format](response))

open_cli/main.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import argparse
44

55
import cli
6+
import formatter
67

78
HISTORY_PATH = os.path.join(os.path.expanduser("~"), ".open-cli")
89

@@ -14,7 +15,8 @@ def main():
1415
args_parser.add_argument('-v', '--verbose', action='store_true', help='If set, set log level to debug')
1516
args_parser.add_argument('-t', '--history', type=str, default=HISTORY_PATH, help='history file path')
1617
args_parser.add_argument('-c', '--command', type=str, help='command to execute', required=False)
17-
args_parser.add_argument('-f', '--format', type=str, choices=['raw', 'table'], default='raw',
18+
args_parser.add_argument('-f', '--format', type=str,
19+
choices=formatter.FORMATTERS.keys(), default=formatter.JSON,
1820
help='Set the CLI output format')
1921
args_parser.add_argument('--header', nargs='+', default=[],
2022
help='requests headers, usage: --header x-header-1:val-1 x-header-2:val2')

0 commit comments

Comments
 (0)