def generate_experiment_jsons(): # read all JSON files from input template JSONs # outputs combined JSON files to output_json folder _input_directory_ = "./jsons/input_json_templates" _output_directory_ = "./jsons/output_exp_jsons" if not os.path.exists(_input_directory_): raise Exception("Absent Input Directory !") if not os.path.exists(_output_directory_): os.makedirs(_output_directory_) else: # clear the contents of the directory shutil.rmtree(_output_directory_) os.makedirs(_output_directory_) json_templates = [f for f in listdir(_input_directory_) if isfile(join(_input_directory_, f))] _json_lists_ = [] common_json_data = {} for temp in json_templates: temp_filename = join(_input_directory_, temp) template = open(temp_filename, 'r') _json_data_ = json.load(template) if isinstance(_json_data_, list): _json_lists_.append(_json_data_) elif isinstance(_json_data_, dict): for key, value in _json_data_.items(): common_json_data[key] = value else: raise Exception("Invalid type of JSON Data ! Only List / Dict allowed ...") count = 0 for combined_json in itertools.product(*_json_lists_): count += 1 json_holder = common_json_data if not(combined_json and json_holder): continue for _dict_ in combined_json: json_holder = json_merge(_dict_, json_holder) new_json_filename = f"experiment_{count}.json" new_json_filename = join(_output_directory_, new_json_filename) with open(new_json_filename, 'w') as outfile: json.dump(json_holder, outfile)
def test_merging_2_dicts_yields_values_from_second_for_collisions(self): a = dict(a=1, b=2, c=3) b = dict(a="x", c="y") self.assertEqual(jsonmerge.json_merge(a, b), dict(a="x", b=2, c="y"))
def test_merging_2_dicts_yields_dict_with_keys_from_both(self): a = dict(a=1, b=2, c=3) b = dict(c=-1, d=-2) self.assertEqual(set(jsonmerge.json_merge(a, b).keys()), set(a.keys()) | set(b.keys()))
def test_merging_2_lists_yields_concatenation_of_both(self): self.assertEqual(jsonmerge.json_merge([1, 2, 3, 4], [5, 6]), [1, 2, 3, 4, 5, 6])
def test_merging_list_with_dict_yields_second(self): self.assertEqual(jsonmerge.json_merge([1, 2], {1: 2}), {1: 2}) self.assertEqual(jsonmerge.json_merge({1: 2}, [1, 2]), [1, 2])
def test_merging_list_with_scalar_yields_second(self): self.assertEqual(jsonmerge.json_merge([1, 2], 123), 123) self.assertEqual(jsonmerge.json_merge(True, [1, 2]), [1, 2])
def test_merging_dict_with_scalar_yields_second(self): self.assertEqual(jsonmerge.json_merge({1: 2}, 123), 123) self.assertEqual(jsonmerge.json_merge(True, {1: 2}), {1: 2})
def test_merging_2_scalar_values_yields_second(self): self.assertEqual(jsonmerge.json_merge(123, 456), 456) self.assertEqual(jsonmerge.json_merge(123, "foo"), "foo") self.assertEqual(jsonmerge.json_merge(123, None), None)