Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion fixit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def run_uuid(args: argparse.Namespace) -> None:

def run_json(args: argparse.Namespace) -> None:
try:
print(jsonfmt.format_json(args.raw))
print(jsonfmt.format_json(args.raw, sort_keys=args.sort_keys))
except ValueError as e:
raise ValueError(f"Error: invalid JSON - {e}")

Expand Down Expand Up @@ -120,6 +120,9 @@ def build_parser() -> argparse.ArgumentParser:

js = sub.add_parser("json", help="pretty-print JSON")
js.add_argument("raw")
js.add_argument(
"--sort-keys", action="store_true", help="sort keys alphabetically"
)

pal = sub.add_parser("palindrome", help="check if text is a palindrome")
pal.add_argument("text")
Expand Down
4 changes: 2 additions & 2 deletions fixit/jsonfmt.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
import json


def format_json(raw: str, indent: int = 2) -> str:
def format_json(raw: str, indent: int = 2, sort_keys: bool = False) -> str:
"""Format a JSON string with indentation.

Example:
format_json('{"name":"Sam"}') returns '{\n "name": "Sam"\n}'.
"""
try:
data = json.loads(raw)
return json.dumps(data, indent=indent)
return json.dumps(data, indent=indent, sort_keys=sort_keys)
except json.JSONDecodeError:
raise ValueError("Invalid JSON")
8 changes: 8 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,11 @@ def test_top_words_command_defaults_to_three(capsys):

assert result == 0
assert capsys.readouterr().out == "one: 1\ntwo: 1\nthree: 1\n"


def test_json_command_sort_keys(capsys):
result = main(["json", '{"b": 1, "a": 2}', "--sort-keys"])

assert result == 0
assert capsys.readouterr().out == '{\n "a": 2,\n "b": 1\n}\n'

7 changes: 7 additions & 0 deletions tests/test_jsonfmt.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,10 @@ def test_format_json():
def test_invalid_json_friendly_error():
with pytest.raises(ValueError, match="Invalid JSON"):
format_json("{not json")


def test_format_json_sort_keys():
raw = '{"b": 1, "a": 2}'
assert format_json(raw, sort_keys=True) == '{\n "a": 2,\n "b": 1\n}'
assert format_json(raw, sort_keys=False) == '{\n "b": 1,\n "a": 2\n}'

Loading