Skip to main content

Set Value in Nested JSON

Description

The set_json_value function sets a value in a nested dictionary (JSON-like structure) using a dot-separated path. This function allows you to update or add new values in a deeply nested structure without manually traversing the levels.

Function Signature:

def set_json_value(data: dict, path: str, value: Any) -> None:

Parameters

  • data (dict): The dictionary (or JSON-like structure) where the value will be set.
  • path (str): A dot-separated string representing the path to the key where the value will be set (e.g., "user.profile.name").
  • value (Any): The value to set at the specified path.

Returns

  • None: This function modifies the input dictionary in-place and does not return a value.

Example Usage

data = {"user": {"profile": {"name": "John"}}}
set_json_value(data, "user.profile.name", "Jane")
print(data["user"]["profile"]["name"]) # Output: Jane

Behavior

  • The function splits the provided path into keys and iteratively accesses each key in the dictionary.
  • If a key is missing or not a dictionary, it creates a new dictionary at that key.
  • Finally, it sets the value at the last key in the path.

Error Handling

  • The function does not raise errors and ensures that any missing keys along the path are created as dictionaries.