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:
parent
dbbf92f331
commit
3a9c15de98
5 changed files with 181 additions and 269 deletions
6
.gitignore
vendored
Normal file
6
.gitignore
vendored
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
*
|
||||||
|
|
||||||
|
!.gitignore
|
||||||
|
|
||||||
|
!*.md
|
||||||
|
!*.py
|
121
LICENSE
121
LICENSE
|
@ -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
41
LICENSE.md
Normal 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.
|
274
json_wrapper.py
274
json_wrapper.py
|
@ -1,194 +1,184 @@
|
||||||
import json
|
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
|
class JsonFile:
|
||||||
def data(self) -> dict:
|
def __init__(self, path: str, **kwargs: Any) -> None:
|
||||||
"""Returns the all data of the json file."""
|
self.path = path
|
||||||
with open(self._fp) as f:
|
self._json_kwargs = kwargs
|
||||||
return json.load(f)
|
|
||||||
|
|
||||||
def dump(self, data: dict) -> None:
|
def open(self, mode: str = "r", /) -> TextIOWrapper:
|
||||||
"""Dumps the data to the json file."""
|
return open(self.path, mode)
|
||||||
with open(self._fp, mode="w") as f:
|
|
||||||
json.dump(data, f, indent=self._indent_size)
|
|
||||||
|
|
||||||
def validate(self) -> None:
|
def dump(self, data: dict, /) -> None:
|
||||||
"""Validates the json file."""
|
"""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:
|
try:
|
||||||
with open(self._fp, mode="r") as f:
|
data = self.data()
|
||||||
data = json.load(f)
|
|
||||||
except (FileNotFoundError, json.JSONDecodeError):
|
|
||||||
with open(self._fp, mode="w") as f:
|
|
||||||
json.dump({}, f)
|
|
||||||
return
|
|
||||||
if not isinstance(data, dict):
|
if not isinstance(data, dict):
|
||||||
with open(self._fp, mode="w") as f:
|
data = {}
|
||||||
json.dump({}, f)
|
self.dump(data)
|
||||||
|
except (FileNotFoundError, json.JSONDecodeError):
|
||||||
|
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
|
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.
|
"""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.
|
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:
|
Args:
|
||||||
path (str): The path to set the value in.
|
path: The path to set the value in.
|
||||||
value (Union[str, int, bool, dict, list, None]): The value to set.
|
value: The value to set.
|
||||||
force (bool): If True, it overrides the path if the path is blocked by a non-dictionary value.
|
force: If True, it overrides the path if the path is blocked by a non-dictionary value.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValueError: If the path is an empty string.
|
ValueError: If the path is an empty string. See note.
|
||||||
TypeError: If the path is blocked by a non-dictionary value and force is False.
|
TypeError: If the path is blocked by a non-dictionary value while force is False.
|
||||||
"""
|
"""
|
||||||
self.validate()
|
data = self.validate()
|
||||||
path, data = [p for p in path.split(".") if p != ""], self.data
|
data_root = data
|
||||||
reference = data
|
|
||||||
|
path = path.split(".") if isinstance(path, str) else path
|
||||||
|
|
||||||
if not path:
|
if not path:
|
||||||
raise ValueError("Path is empty.")
|
raise ValueError("Path is empty.")
|
||||||
|
|
||||||
|
# All except the last.
|
||||||
for p in path[:-1]:
|
for p in path[:-1]:
|
||||||
if p not in data.keys():
|
if p not in data:
|
||||||
data[p] = {}
|
data[p] = {}
|
||||||
|
|
||||||
elif not isinstance(data[p], dict):
|
elif not isinstance(data[p], dict):
|
||||||
if force:
|
if force:
|
||||||
data[p] = {}
|
data[p] = {}
|
||||||
else:
|
else:
|
||||||
raise TypeError("Path is blocked by a non-dictionary value. Use force=True to override.")
|
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.
|
"""Removes the key in given path.
|
||||||
|
|
||||||
Args:
|
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:
|
Returns:
|
||||||
bool: True if the key was removed, False if the key was not found.
|
bool: True if the key was removed, False if the key was not found.
|
||||||
"""
|
"""
|
||||||
self.validate()
|
data = self.validate()
|
||||||
path, data = [p for p in path.split(".") if p != ""], self.data
|
data_root = data
|
||||||
reference = data
|
|
||||||
|
path = path.split(".") if isinstance(path, str) else path
|
||||||
|
|
||||||
if not path:
|
if not path:
|
||||||
if data:
|
if data:
|
||||||
self.dump({})
|
self.dump({})
|
||||||
return True
|
return True
|
||||||
|
|
||||||
return False
|
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
|
return False
|
||||||
elif not isinstance(data[p], dict):
|
|
||||||
return False
|
data = data[part]
|
||||||
data = data[p]
|
|
||||||
if path[-1] not in data.keys():
|
if path[-1] not in data:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
del data[path[-1]]
|
del data[path[-1]]
|
||||||
self.dump(reference)
|
|
||||||
|
self.dump(data_root)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def __contains__(self, key: str) -> bool:
|
def __getitem__(self, key: str, /) -> JsonType:
|
||||||
self.validate()
|
return self.validate()[key]
|
||||||
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 __setitem__(self, key: str, value: Union[str, int, bool, dict, list, None]) -> None:
|
def __setitem__(self, key: str, value: Union[str, int, bool, dict, list, None]) -> None:
|
||||||
self.validate()
|
data = self.validate()
|
||||||
data = self.data
|
|
||||||
data[key] = value
|
data[key] = value
|
||||||
self.dump(data)
|
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:
|
def __sizeof__(self) -> bytes:
|
||||||
self.validate()
|
return self.validate().__sizeof__()
|
||||||
return bytes(self.data)
|
|
||||||
|
|
8
setup.py
8
setup.py
|
@ -1,17 +1,13 @@
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from setuptools import setup
|
from setuptools import setup
|
||||||
|
|
||||||
this_directory = Path(__file__).parent
|
|
||||||
long_description = (this_directory / "README.md").read_text()
|
|
||||||
|
|
||||||
setup(
|
setup(
|
||||||
name="json_wrapper",
|
name="json_wrapper",
|
||||||
description="Easy to use JSON wrapper packed with features.",
|
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',
|
long_description_content_type='text/markdown',
|
||||||
url="https://github.com/RGBCube/json_wrapper",
|
url="https://github.com/RGBCube/json_wrapper",
|
||||||
version="1.2.0",
|
version="1.3.0",
|
||||||
author="RGBCube",
|
author="RGBCube",
|
||||||
py_modules=["json_wrapper"],
|
py_modules=["json_wrapper"],
|
||||||
license="CC0 1.0 Universal"
|
license="CC0 1.0 Universal"
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue