Skip to content

Commit 6dbd28a

Browse files
committed
Adds add_field_to_json to utils.py
It also adds the corresponding unit test
1 parent b6eedc7 commit 6dbd28a

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

heudiconv/tests/test_utils.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
load_json,
1111
create_tree,
1212
save_json,
13+
add_field_to_json,
1314
get_datetime,
1415
JSONDecodeError)
1516

@@ -88,6 +89,32 @@ def test_load_json(tmpdir, caplog):
8889
assert load_json(valid_json_file) == vcontent
8990

9091

92+
def test_add_field_to_json(tmpdir):
93+
"""
94+
Test utils.add_field_to_json()
95+
"""
96+
dummy_json_file = str(tmpdir / 'dummy.json')
97+
some_content = {"name": "Jason", "age": 30, "city": "New York"}
98+
save_json(dummy_json_file, some_content, pretty=True)
99+
100+
added_content = {"LastName": "Bourne",
101+
"Movies": [
102+
"The Bourne Identity",
103+
"The Bourne Supremacy",
104+
"The Bourne Ultimatum",
105+
"The Bourne Legacy",
106+
"Jason Bourne"
107+
]
108+
}
109+
add_field_to_json(dummy_json_file, added_content)
110+
111+
# check that it was added:
112+
with open(dummy_json_file) as f:
113+
data = json.load(f)
114+
some_content.update(added_content)
115+
assert data == some_content
116+
117+
91118
def test_get_datetime():
92119
"""
93120
Test utils.get_datetime()

heudiconv/utils.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,32 @@ def json_dumps_pretty(j, indent=2, sort_keys=True):
264264
return js_
265265

266266

267+
def add_field_to_json(json_file, field_and_value):
268+
"""
269+
Adds a given field (and its value) to a json file
270+
271+
Parameters:
272+
-----------
273+
json_file : str or Path
274+
path for the corresponding json file
275+
field_and_value : dict
276+
pair of "key": "value" to add to the json file
277+
"""
278+
for key, value in field_and_value.items():
279+
lgr.debug(
280+
'File: "{f}": Adding {k}: {v}'.format(
281+
f=json_file,
282+
k=key,
283+
v=value,
284+
)
285+
)
286+
287+
with open(json_file) as f:
288+
data = json.load(f)
289+
data.update(field_and_value)
290+
save_json(json_file, data, pretty=True)
291+
292+
267293
def treat_infofile(filename):
268294
"""Tune up generated .json file (slim down, pretty-print for humans).
269295
"""

0 commit comments

Comments
 (0)