Skip to content

Commit

Permalink
Support formatting options in get_json_string()
Browse files Browse the repository at this point in the history
This change passes through keyword arguments to json.dumps() in a
similar manner to get_csv_string(). Additionally, it respects the
'header' table option.
  • Loading branch information
kluelesskk committed Nov 16, 2020
1 parent 9a7c748 commit 251ddee
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
19 changes: 14 additions & 5 deletions src/prettytable/prettytable.py
Expand Up @@ -1555,17 +1555,26 @@ def get_json_string(self, **kwargs):

"""Return string representation of JSON formatted table in the current state
Arguments:
none yet"""
Keyword arguments are first interpreted as table formatting options, and
then any unused keyword arguments are passed to json.dumps(). For
example, get_json_string(header=False, indent=2) would use header as
a PrettyTable formatting option (skip the header row) and indent as a
json.dumps keyword argument.
"""

options = self._get_options(kwargs)
json_options = dict(indent=4, separators=(",", ": "), sort_keys=True)
json_options.update(
{key: value for key, value in kwargs.items() if key not in options}
)
objects = []

objects = [self.field_names]
if options.get("header"):
objects.append(self.field_names)
for row in self._get_rows(options):
objects.append(dict(zip(self._field_names, row)))

return json.dumps(objects, indent=4, separators=(",", ": "), sort_keys=True)
return json.dumps(objects, **json_options)

##############################
# HTML STRING METHODS #
Expand Down
10 changes: 10 additions & 0 deletions tests/test_prettytable.py
Expand Up @@ -601,6 +601,16 @@ def testJSONOutput(self):
]""".strip()
)

def testJSONOutputOptions(self):
t = helper_table()
result = t.get_json_string(header=False, indent=None, separators=(",", ":"))
assert (
result
== """[{"Field 1":"value 1","Field 2":"value2","Field 3":"value3"},"""
"""{"Field 1":"value 4","Field 2":"value5","Field 3":"value6"},"""
"""{"Field 1":"value 7","Field 2":"value8","Field 3":"value9"}]"""
)


class HtmlOutputTests(unittest.TestCase):
def testHtmlOutput(self):
Expand Down

0 comments on commit 251ddee

Please sign in to comment.