1
Fork 0
mirror of https://github.com/RGBCube/JsonWrapper synced 2025-07-27 11:47:45 +00:00

1.3.0: Cleanup

This commit is contained in:
RGBCube 2023-04-28 22:45:48 +03:00 committed by GitHub
parent dbbf92f331
commit 3a9c15de98
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 181 additions and 269 deletions

6
.gitignore vendored Normal file
View file

@ -0,0 +1,6 @@
*
!.gitignore
!*.md
!*.py

121
LICENSE
View file

@ -1,121 +0,0 @@
Creative Commons Legal Code
CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.

41
LICENSE.md Normal file
View file

@ -0,0 +1,41 @@
# Creative Commons CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER.
## Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
1. __Copyright and Related Rights.__ A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
2. __Waiver.__ To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose.
3. __Public License Fallback.__ Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose.
4. __Limitations and Disclaimers.__
a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work.

View file

@ -1,194 +1,184 @@
import json
from typing import Any, Union
from io import TextIOWrapper
from typing import Any
class JsonBase:
JsonType = str | int | bool | dict | list | None
def __init__(self, *, fp: str, indent: int) -> None:
self._fp = fp
self._indent_size = indent
@property
def data(self) -> dict:
"""Returns the all data of the json file."""
with open(self._fp) as f:
return json.load(f)
class JsonFile:
def __init__(self, path: str, **kwargs: Any) -> None:
self.path = path
self._json_kwargs = kwargs
def dump(self, data: dict) -> None:
"""Dumps the data to the json file."""
with open(self._fp, mode="w") as f:
json.dump(data, f, indent=self._indent_size)
def open(self, mode: str = "r", /) -> TextIOWrapper:
return open(self.path, mode)
def validate(self) -> None:
"""Validates the json file."""
def dump(self, data: dict, /) -> None:
"""Dumps the data to the JSON file."""
with self.open("w") as file:
json.dump(data, file, **self._json_kwargs)
def data(self) -> dict[Any, Any]:
"""Returns the all data in the JSON file."""
with self.open() as file:
return json.load(file, **self._json_kwargs)
def validate(self) -> dict:
"""Validates the JSON file contents and returns them."""
try:
with open(self._fp, mode="r") as f:
data = json.load(f)
data = self.data()
if not isinstance(data, dict):
data = {}
self.dump(data)
except (FileNotFoundError, json.JSONDecodeError):
with open(self._fp, mode="w") as f:
json.dump({}, f)
return
if not isinstance(data, dict):
with open(self._fp, mode="w") as f:
json.dump({}, f)
data = {}
self.dump(data)
class JsonWrapper(JsonBase):
def __init__(self, fp: str, *, indent: int = 4) -> None:
super().__init__(fp=fp, indent=indent)
self.validate()
def get(self, path: str = "", default: Any = None) -> Union[str, int, bool, dict, list, None]:
"""Returns the value of the key in given path. If the key is not found in the path, returns the default value.
Args:
path (str): The path to the key. If the path is not given, returns the whole json as a dict.
default (Any): The default value.
Returns:
Union[str, int, bool, dict, list, None]: The value of the key in given path.
"""
self.validate()
path, data = [p for p in path.split(".") if p != ""], self.data
for p in path:
if p not in data:
return default
data = data[p]
return data
def set(self, path: str, value: Union[str, int, bool, dict, list, None], *, force: bool = False) -> None:
class JsonWrapper(JsonFile):
def __init__(self, path: str, /, *, indent: int = 4) -> None:
super().__init__(path, indent=indent)
self.validate()
def get(self, path: str | list[str] = [], /, default: Any = None) -> JsonType:
"""
Returns the value of the key in given path. If the key is not found in the path, returns the default value.
For example, if `jw.get("foo.bar.baz")` is called and the JSON is `{"foo": {"bar": {"baz": 123}}}`, `123` will be returned.
Args:
path: The path to the key. If not given, returns the whole JSON.
default: The default value.
Returns:
The value of the key in given path.
"""
data = self.validate()
path = path.split(".") if isinstance(path, str) else path
for part in path:
if part not in data:
return default
data = data[p]
return data
def set(self, path: str | list[str], value: JsonType, /, *, force: bool = False) -> None:
"""Sets the path to the value. If the path is not found, creates the path.
If the path is blocked by a non-dictionary value, it will raise TypeError, to override this behavior, set force to True.
Note: Use `JsonWrapper.dump` if you want to set the whole JSON to a dict.
Args:
path (str): The path to set the value in.
value (Union[str, int, bool, dict, list, None]): The value to set.
force (bool): If True, it overrides the path if the path is blocked by a non-dictionary value.
path: The path to set the value in.
value: The value to set.
force: If True, it overrides the path if the path is blocked by a non-dictionary value.
Raises:
ValueError: If the path is an empty string.
TypeError: If the path is blocked by a non-dictionary value and force is False.
ValueError: If the path is an empty string. See note.
TypeError: If the path is blocked by a non-dictionary value while force is False.
"""
self.validate()
path, data = [p for p in path.split(".") if p != ""], self.data
reference = data
data = self.validate()
data_root = data
path = path.split(".") if isinstance(path, str) else path
if not path:
raise ValueError("Path is empty.")
# All except the last.
for p in path[:-1]:
if p not in data.keys():
if p not in data:
data[p] = {}
elif not isinstance(data[p], dict):
if force:
data[p] = {}
else:
raise TypeError("Path is blocked by a non-dictionary value. Use force=True to override.")
data = data[p]
data[path[-1]] = value
self.dump(reference)
def rem(self, path: str = "") -> bool:
data = data[p]
data[path[-1]] = value
self.dump(data_root)
def rem(self, path: str | list[str] = [], /) -> bool:
"""Removes the key in given path.
Args:
path (str): The path to the key. If the path is not given, nukes the whole json.
path: The path to the key. If the path is not given, nukes the whole json.
Returns:
bool: True if the key was removed, False if the key was not found.
"""
self.validate()
path, data = [p for p in path.split(".") if p != ""], self.data
reference = data
data = self.validate()
data_root = data
path = path.split(".") if isinstance(path, str) else path
if not path:
if data:
self.dump({})
return True
return False
for p in path[:-1]:
if p not in data.keys():
# All except the last.
for part in path[:-1]:
if part not in data or not isinstance(data[part], dict):
return False
elif not isinstance(data[p], dict):
return False
data = data[p]
if path[-1] not in data.keys():
data = data[part]
if path[-1] not in data:
return False
del data[path[-1]]
self.dump(reference)
self.dump(data_root)
return True
def __contains__(self, key: str) -> bool:
self.validate()
return key in self.data
def __delitem__(self, key: str) -> None:
self.validate()
data = self.data
del data[key]
self.dump(data)
def __eq__(self, other: Any) -> bool:
return self.data == other
def __getitem__(self, key: str) -> Union[str, int, bool, dict, list, None]:
self.validate()
return self.data[key]
def __ge__(self, other: Any) -> bool:
self.validate()
return self.data >= other
def __gt__(self, other: Any) -> bool:
self.validate()
return self.data > other
def __ior__(self, other) -> None:
self.validate()
data = self.data
data.update(other)
self.dump(data)
def __iter__(self):
self.validate()
return iter(self.data)
def __len__(self) -> int:
self.validate()
return len(self.data)
def __le__(self, other: Any) -> bool:
self.validate()
return self.data <= other
def __lt__(self, other: Any) -> bool:
self.validate()
return self.data < other
def __ne__(self, other: Any) -> bool:
self.validate()
return self.data != other
def __or__(self, other: Any) -> Any:
self.validate()
return self.data | other
def __repr__(self) -> str:
self.validate()
return repr(self.data)
def __reversed__(self):
self.validate()
return reversed(self.data)
def __ror__(self, other: Any) -> bool:
self.validate()
return other | self.data
def __getitem__(self, key: str, /) -> JsonType:
return self.validate()[key]
def __setitem__(self, key: str, value: Union[str, int, bool, dict, list, None]) -> None:
self.validate()
data = self.data
data = self.validate()
data[key] = value
self.dump(data)
def __delitem__(self, key: str, /) -> None:
data = self.validate()
del data[key]
self.dump(data)
def __contains__(self, key: str, /) -> bool:
return key in self.validate()
def __repr__(self) -> str:
return repr(self.validate())
def __str__(self) -> str:
return str(self.validate())
def __reversed__(self):
return reversed(self.validate())
def __eq__(self, other: Any, /) -> bool:
return self.data == other
def __ior__(self, other: Any) -> bool:
data = self.validate()
data |= other
self.dump(data)
def __ror__(self, other: Any) -> bool:
return other | self.validate()
def __sizeof__(self) -> bytes:
self.validate()
return bytes(self.data)
return self.validate().__sizeof__()

View file

@ -1,17 +1,13 @@
from pathlib import Path
from setuptools import setup
this_directory = Path(__file__).parent
long_description = (this_directory / "README.md").read_text()
setup(
name="json_wrapper",
description="Easy to use JSON wrapper packed with features.",
long_description=long_description,
long_description=(Path(__file__).parent / "README.md").read_text(),
long_description_content_type='text/markdown',
url="https://github.com/RGBCube/json_wrapper",
version="1.2.0",
version="1.3.0",
author="RGBCube",
py_modules=["json_wrapper"],
license="CC0 1.0 Universal"