combine a list of json to a single json, which is the most consistent on the given keys :param json_list: a list of similar json with same keys but possible different values :param keys: a list of keys needs to be consistent :param mode: consistency mode of keys, accept "all" or "ea
(json_list, keys, mode)
| 63 | |
| 64 | |
| 65 | def combine_json(json_list, keys, mode): |
| 66 | """ |
| 67 | combine a list of json to a single json, which is the most consistent on the given keys |
| 68 | :param json_list: a list of similar json with same keys but possible different values |
| 69 | :param keys: a list of keys needs to be consistent |
| 70 | :param mode: consistency mode of keys, accept "all" or "each" |
| 71 | :return: a consistent json and the vote statistics |
| 72 | """ |
| 73 | |
| 74 | if not json_list or not json_list[0]: |
| 75 | return None, None |
| 76 | |
| 77 | if not keys: |
| 78 | keys = list(json_list[0].keys()) |
| 79 | |
| 80 | consistent_json, vote_statistics = {}, {} |
| 81 | |
| 82 | values_list = [] |
| 83 | for json_obj in json_list: |
| 84 | key_values = [str(json_obj[key]) for key in keys if key in json_obj] |
| 85 | values_list.append(tuple(key_values)) |
| 86 | |
| 87 | if mode == "all": |
| 88 | most_consistent_values, vote_statistics_list = get_most_voted_values(values_list, mode) |
| 89 | consistent_json = dict(zip(keys, list(map(convert_str_to_element, most_consistent_values)))) |
| 90 | vote_statistics = vote_statistics_list |
| 91 | |
| 92 | elif mode == "each": |
| 93 | values_list_transpose = list(zip(*values_list)) |
| 94 | most_consistent_values, vote_statistics_list = get_most_voted_values(values_list_transpose, mode) |
| 95 | consistent_json = dict(zip(keys, list(map(convert_str_to_element, most_consistent_values)))) |
| 96 | vote_statistics = dict(zip(keys, [stat for stat in vote_statistics_list])) |
| 97 | |
| 98 | return consistent_json, vote_statistics |
| 99 | |
| 100 | |
| 101 | # examples |
no test coverage detected