mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-04-06 12:06:53 +00:00
Merge pull request #558 from AdityaKhursale/master
Report duplicate keys in check_json
This commit is contained in:
commit
cefb9ed975
3 changed files with 22 additions and 1 deletions
|
|
@ -1,7 +1,23 @@
|
||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
|
from typing import Any
|
||||||
|
from typing import Dict
|
||||||
|
from typing import List
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from typing import Sequence
|
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:
|
def main(argv: Optional[Sequence[str]] = None) -> int:
|
||||||
|
|
@ -13,7 +29,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
|
||||||
for filename in args.filenames:
|
for filename in args.filenames:
|
||||||
with open(filename, 'rb') as f:
|
with open(filename, 'rb') as f:
|
||||||
try:
|
try:
|
||||||
json.load(f)
|
json.load(f, object_pairs_hook=raise_duplicate_keys)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
print(f'{filename}: Failed to json decode ({exc})')
|
print(f'{filename}: Failed to json decode ({exc})')
|
||||||
retval = 1
|
retval = 1
|
||||||
|
|
|
||||||
4
testing/resources/duplicate_key_json.json
Normal file
4
testing/resources/duplicate_key_json.json
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
{
|
||||||
|
"hello": "world",
|
||||||
|
"hello": "planet"
|
||||||
|
}
|
||||||
|
|
@ -9,6 +9,7 @@ from testing.util import get_resource_path
|
||||||
('bad_json.notjson', 1),
|
('bad_json.notjson', 1),
|
||||||
('bad_json_latin1.nonjson', 1),
|
('bad_json_latin1.nonjson', 1),
|
||||||
('ok_json.json', 0),
|
('ok_json.json', 0),
|
||||||
|
('duplicate_key_json.json', 1),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
def test_main(capsys, filename, expected_retval):
|
def test_main(capsys, filename, expected_retval):
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue