Skip to content

Commit

Permalink
Report duplicate keys in check_json
Browse files Browse the repository at this point in the history
Raise ValueError and return 1 if json contains duplicate keys
  • Loading branch information
AdityaKhursale authored and asottile committed Feb 18, 2021
1 parent 11a2fdb commit fe37451
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
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

0 comments on commit fe37451

Please sign in to comment.