Skip to content

Commit fe37451

Browse files
AdityaKhursaleasottile
authored andcommitted
Report duplicate keys in check_json
Raise ValueError and return 1 if json contains duplicate keys
1 parent 11a2fdb commit fe37451

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

pre_commit_hooks/check_json.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,23 @@
11
import argparse
22
import json
3+
from typing import Any
4+
from typing import Dict
5+
from typing import List
36
from typing import Optional
47
from typing import Sequence
8+
from typing import Tuple
9+
10+
11+
def raise_duplicate_keys(
12+
ordered_pairs: List[Tuple[str, Any]],
13+
) -> Dict[str, Any]:
14+
d = {}
15+
for key, val in ordered_pairs:
16+
if key in d:
17+
raise ValueError(f'Duplicate key: {key}')
18+
else:
19+
d[key] = val
20+
return d
521

622

723
def main(argv: Optional[Sequence[str]] = None) -> int:
@@ -13,7 +29,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
1329
for filename in args.filenames:
1430
with open(filename, 'rb') as f:
1531
try:
16-
json.load(f)
32+
json.load(f, object_pairs_hook=raise_duplicate_keys)
1733
except ValueError as exc:
1834
print(f'{filename}: Failed to json decode ({exc})')
1935
retval = 1
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"hello": "world",
3+
"hello": "planet"
4+
}

tests/check_json_test.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
('bad_json.notjson', 1),
1010
('bad_json_latin1.nonjson', 1),
1111
('ok_json.json', 0),
12+
('duplicate_key_json.json', 1),
1213
),
1314
)
1415
def test_main(capsys, filename, expected_retval):

0 commit comments

Comments
 (0)