From 98c96766a3ab5e641d1860f5f7a15881ecc58447 Mon Sep 17 00:00:00 2001 From: marupakalaharsith20-beep <242739440+marupakalaharsith20-beep@users.noreply.github.com> Date: Sun, 25 Oct 2026 12:52:36 +0530 Subject: [PATCH] feat(json): add --sort-keys option to json command (closes #16) --- fixit/cli.py | 5 ++++- fixit/jsonfmt.py | 4 ++-- tests/test_cli.py | 8 ++++++++ tests/test_jsonfmt.py | 7 +++++++ 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/fixit/cli.py b/fixit/cli.py index 52d4ffb..50c9d7b 100644 --- a/fixit/cli.py +++ b/fixit/cli.py @@ -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}") @@ -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") diff --git a/fixit/jsonfmt.py b/fixit/jsonfmt.py index 89ba00f..04a5947 100644 --- a/fixit/jsonfmt.py +++ b/fixit/jsonfmt.py @@ -3,7 +3,7 @@ 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: @@ -11,6 +11,6 @@ def format_json(raw: str, indent: int = 2) -> str: """ 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") diff --git a/tests/test_cli.py b/tests/test_cli.py index 532b78e..5048725 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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' + diff --git a/tests/test_jsonfmt.py b/tests/test_jsonfmt.py index dbdb514..ffc89d8 100644 --- a/tests/test_jsonfmt.py +++ b/tests/test_jsonfmt.py @@ -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}' +