22
33import json
44from pathlib import Path
5- from typing import Any , cast , Dict , Hashable , List , Tuple , Union
5+ from typing import Any , Hashable , List , Tuple , Union
66
77from owid .datautils .common import warn_on_list_of_entities
88
99
1010def _load_json_data_and_duplicated_keys (
1111 ordered_pairs : List [Tuple [Hashable , Any ]]
12- ) -> Tuple [ Dict [ Any , Any ], List [ Any ]] :
12+ ) -> Any :
1313 clean_dict = {}
1414 duplicated_keys = []
1515 for key , value in ordered_pairs :
1616 if key in clean_dict :
1717 duplicated_keys .append (key )
1818 clean_dict [key ] = value
19+ if len (duplicated_keys ) > 0 :
20+ warn_on_list_of_entities (
21+ list_of_entities = duplicated_keys ,
22+ warning_message = "Duplicated entities found." ,
23+ show_list = True ,
24+ )
1925
20- return clean_dict , duplicated_keys
26+ return clean_dict
2127
2228
23- def load_json (
24- json_file : Union [str , Path ], warn_on_duplicated_keys : bool = True
25- ) -> Dict [Any , Any ]:
29+ def load_json (json_file : Union [str , Path ], warn_on_duplicated_keys : bool = True ) -> Any :
2630 """Load data from json file, and optionally warn if there are duplicated keys.
2731
28- If json file contains duplicated keys, a warning is optionally raised, and only the latest value of the key is kept.
32+ If json file contains duplicated keys, a warning is optionally raised, and only the value of the latest duplicated
33+ key is kept.
2934
3035 Parameters
3136 ----------
@@ -41,20 +46,15 @@ def load_json(
4146
4247 """
4348 with open (json_file , "r" ) as _json_file :
49+ json_content = _json_file .read ()
4450 if warn_on_duplicated_keys :
45- data , duplicated_keys = json .loads (
46- _json_file . read () , object_pairs_hook = _load_json_data_and_duplicated_keys
51+ data = json .loads (
52+ json_content , object_pairs_hook = _load_json_data_and_duplicated_keys
4753 )
48- if len (duplicated_keys ) > 0 :
49- warn_on_list_of_entities (
50- duplicated_keys ,
51- f"Duplicated entities found in { json_file } " ,
52- show_list = True ,
53- )
5454 else :
55- data = json .loads (_json_file . read () )
55+ data = json .loads (json_content )
5656
57- return cast ( Dict [ Any , Any ], data )
57+ return data
5858
5959
6060def save_json (data : Any , json_file : Union [str , Path ], ** kwargs : Any ) -> None :
0 commit comments