Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Report duplicate keys in check_json #558

Merged
merged 1 commit into from Feb 18, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 17 additions & 1 deletion pre_commit_hooks/check_json.py
@@ -1,7 +1,23 @@
import argparse
import json
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Sequence
from typing import Tuple


def raise_duplicate_keys(
ordered_pairs: List[Tuple[str, Any]],
) -> Dict[str, Any]:
d = {}
for key, val in ordered_pairs:
if key in d:
raise ValueError(f'Duplicate key: {key}')
else:
d[key] = val
return d


def main(argv: Optional[Sequence[str]] = None) -> int:
Expand All @@ -13,7 +29,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
for filename in args.filenames:
with open(filename, 'rb') as f:
try:
json.load(f)
json.load(f, object_pairs_hook=raise_duplicate_keys)
except ValueError as exc:
print(f'{filename}: Failed to json decode ({exc})')
retval = 1
Expand Down
4 changes: 4 additions & 0 deletions testing/resources/duplicate_key_json.json
@@ -0,0 +1,4 @@
{
"hello": "world",
"hello": "planet"
}
1 change: 1 addition & 0 deletions tests/check_json_test.py
Expand Up @@ -9,6 +9,7 @@
('bad_json.notjson', 1),
('bad_json_latin1.nonjson', 1),
('ok_json.json', 0),
('duplicate_key_json.json', 1),
),
)
def test_main(capsys, filename, expected_retval):
Expand Down