Skip to content

Commit 478d6a2

Browse files
committed
fixed issue with delimiter and added docstring
1 parent 213dd95 commit 478d6a2

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

localstack-core/localstack/utils/json.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,15 +169,24 @@ def extract_jsonpath(value, path):
169169
return result
170170

171171

172-
def assign_to_path(target, path: str, value, delimiter: str = "."):
172+
def assign_to_path(target: dict, path: str, value: any, delimiter: str = ".") -> dict:
173+
"""Assign the given value to a dict. If the path doesn't exist in the target dict, it will be created.
174+
The delimiter can be used to provide a path with a different delimiter.
175+
176+
Examples:
177+
- assign_to_path({}, "a", "b") => {"a": "b"}
178+
- assign_to_path({}, "a.b.c", "d") => {"a": {"b": {"c": "d"}}}
179+
- assign_to_path({}, "a.b/c", "d", delimiter="/") => {"a.b": {"c": "d"}}
180+
181+
"""
173182
parts = path.strip(delimiter).split(delimiter)
174183

175184
if len(parts) == 1:
176185
target[parts[0]] = value
177186
return target
178187

179188
path_to_parent = delimiter.join(parts[:-1])
180-
parent = extract_from_jsonpointer_path(target, path_to_parent, auto_create=True)
189+
parent = extract_from_jsonpointer_path(target, path_to_parent, delimiter, auto_create=True)
181190
if not isinstance(parent, dict):
182191
LOG.debug(
183192
'Unable to find parent (type %s) for path "%s" in object: %s',

tests/unit/utils/test_json.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,17 @@ def test_json_encoder():
1111

1212
def test_assign_to_path_single_path():
1313
target = {}
14-
assign_to_path(target, "foo", "bar")
15-
assert target == {"foo": "bar"}
14+
assign_to_path(target, "a", "bar")
15+
assert target == {"a": "bar"}
16+
17+
18+
def test_assign_multi_nested_path():
19+
target = {}
20+
assign_to_path(target, "a.b.foo", "bar")
21+
assert target == {"a": {"b": {"foo": "bar"}}}
22+
23+
24+
def test_assign_to_path_mixed_delimiters():
25+
target = {}
26+
assign_to_path(target, "a.b/c", "d", delimiter="/")
27+
assert target == {"a.b": {"c": "d"}}

0 commit comments

Comments
 (0)