-
Notifications
You must be signed in to change notification settings - Fork 14
Add helper to update JSON files safely #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
howbootcamps
wants to merge
1
commit into
main
Choose a base branch
from
codex/implement-update_json_file-function
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| """Utilities for updating JSON files.""" | ||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import os | ||
| from collections.abc import Mapping | ||
| from typing import Any | ||
|
|
||
|
|
||
| def update_json_file(path: str, new_data: Mapping[str, Any]) -> bool: | ||
| """Update JSON keys in ``path`` with values from ``new_data``. | ||
|
|
||
| The function reads the current JSON content from ``path``. If the file does not | ||
| exist, it is created with ``new_data`` as its content. When the file exists, only | ||
| keys already present in the JSON document are updated. Other keys in | ||
| ``new_data`` are ignored so the structure of the original document is | ||
| preserved. | ||
|
|
||
| Args: | ||
| path: Path to the JSON file that should be updated. | ||
| new_data: Mapping containing key/value pairs to update. | ||
|
|
||
| Returns: | ||
| ``True`` if the update succeeds, otherwise ``False``. | ||
| """ | ||
|
|
||
| if not isinstance(new_data, Mapping): | ||
| return False | ||
|
|
||
| try: | ||
| existing_data: dict[str, Any] = {} | ||
| file_exists = os.path.exists(path) | ||
|
|
||
| if file_exists: | ||
| with open(path, "r", encoding="utf-8") as file: | ||
| content = file.read().strip() | ||
|
|
||
| if content: | ||
| loaded = json.loads(content) | ||
| if not isinstance(loaded, dict): | ||
| return False | ||
| existing_data = loaded | ||
| else: | ||
| directory = os.path.dirname(path) | ||
| if directory: | ||
| os.makedirs(directory, exist_ok=True) | ||
|
|
||
| if file_exists: | ||
| for key, value in new_data.items(): | ||
| if key in existing_data: | ||
| existing_data[key] = value | ||
| else: | ||
| existing_data = dict(new_data) | ||
|
|
||
| with open(path, "w", encoding="utf-8") as file: | ||
| json.dump(existing_data, file, ensure_ascii=False, indent=4) | ||
| file.write("\n") | ||
|
|
||
| return True | ||
| except (OSError, json.JSONDecodeError): | ||
| return False | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When the target file exists, the loop replaces an entire value whenever the top-level key is present. If that value is itself a dictionary, providing a partial update will clobber unspecified nested keys. For example, an existing document
{ "settings": { "theme": "dark", "lang": "en" } }updated withnew_data={"settings": {"lang": "fr"}}results in{"settings": {"lang": "fr"}}, losingtheme. This contradicts the docstring’s promise to preserve the original structure and can silently drop data. A recursive merge is needed to update only the provided nested keys.Useful? React with 👍 / 👎.