1
Fork 0
mirror of https://github.com/RGBCube/JsonWrapper synced 2025-07-27 11:47:45 +00:00
This commit is contained in:
RGBCube 2022-01-27 17:48:01 +03:00
parent 28118d7959
commit 6754fac5c8
3 changed files with 224 additions and 260 deletions

179
README.md
View file

@ -1,183 +1,12 @@
# 🈷️ JsonWrapper # 🈷️ JsonWrapper
Easy to use JSON wrapper packed with features. Easy to use JSON wrapper packed with features.
View it on PyPi: https://pypi.org/project/json-wrapper/
# 📥 Usage # 📥 Usage
Execute `pip install json-wrapper`. Execute `pip install json-wrapper`.
Add `from json_wrapper import JsonWrapper` to the top of your project. Add `from json_wrapper import JsonWrapper` to the top of your project.
# 📄 Docs # 🔗 Important Links
> Assume that we did `db = JsonWrapper("example.json")` [ReadTheDocs: json-wrapper]() TODO
## `db.set(key: str, value, *, pathmagic="")`
Sets the key to the value in the JSON.
if the `pathmagic` kwarg is given, it will spit it by the `+`'s and make dicts(or use existing ones) until it finishes, then it will set the value to the key in the last dict. [PyPI: json-wrapper](https://pypi.org/project/json-wrapper/)
Note that the `pathmagic` kwarg will override its path if it isnt a dict. [GitHub: RGBCube/json-wrapper](https://github.com/RGBCube/json-wrapper)
## `db.get(key: str, *, default=None, pathmagic="")`
Returns the value of the key in the json, if the key isn't set in the json, it returns the default kwarg.
if the `pathmagic` kwarg is given, it will spit it by the `+`'s and follow the path in it in the JSON data, it will return the `default` kwarg if the path is empty or has a value that isnt a dict.
## `db.all()`
Returns all the JSON data.
## `db.rem(key: str, *, pathmagic="")`
Removes the key and value pair from the JSON.
Note that this will not do anything if the key isn't set in the JSON or the path is invalid.
if the `pathmagic` kwarg is given, it will spit it by the `+`'s and follow the path in it in the JSON data, then it will remove the key and value pair.
## `db.nuke()`
Deletes everything in the JSON.
Use with caution.
# 📘 Examples
> Assume that the `example.json` file is empty
## `db.set()`
### Normal usage
Code
```python
from json_wrapper import JsonWrapper
db = JsonWrapper("example.json")
db.set("test", 123)
data = db.all()
print(data)
```
Output
```
{'test': 123}
```
### Using with `pathmagic` kwarg
Code
```python
from json_wrapper import JsonWrapper
db = JsonWrapper("example.json")
db.set("test", 123, pathmagic="a+b+c")
data = db.all()
print(data)
```
Output
```
{'a': {'b': {'c': {'test': 123}}}}
```
## `db.get()`
### Normal usage
Code
```python
from json_wrapper import JsonWrapper
db = JsonWrapper("example.json")
db.set("test", 123)
data = db.get("test")
print(data)
```
Output
```
123
```
### Using without `default` kwarg
Code
```python
from json_wrapper import JsonWrapper
db = JsonWrapper("example.json")
data = db.get("test")
print(data)
```
Output
```
None
```
### Using with `default` kwarg
Code
```python
from json_wrapper import JsonWrapper
db = JsonWrapper("example.json")
data = db.get("test", default=123)
print(data)
```
Output
```
123
```
### Using with `pathmagic` kwarg
Code
```python
from json_wrapper import JsonWrapper
db = JsonWrapper("example.json")
db.set("test", 123, pathmagic="a+b+c")
data = db.get("test", pathmagic="a+b+c")
print(data)
```
Output
```
123
```
## `db.rem()`
### Normal usage
Code
```python
from json_wrapper import JsonWrapper
db = JsonWrapper("example.json")
db.set("test", 123)
data = db.all()
print(data)
db.rem("test")
data = db.all()
print(data)
```
Output
```
{'test': 123}
{}
```
### Using with `pathmagic` kwarg
Code
```python
from json_wrapper import JsonWrapper
db = JsonWrapper("example.json")
db.set("test", 123, pathmagic="a+b+c")
data = db.all()
print(data)
db.rem("test", pathmagic="a+b+c")
data = db.all()
print(data)
```
Output
```
{'a': {'b': {'c': {'test': 123}}}}
{'a': {'b': {'c': {}}}}
```

View file

@ -1,101 +1,236 @@
import json import json
import os import os
from typing import Any, Union, List
class Utils: class _JsonUtils:
def __init__(self, json_path: str) -> None:
self.json_path = json_path
def data(self) -> dict:
"""Returns all the json data.
Returns:
dict: All the json data.
"""
with open(self.json_path, mode="r") as json_file:
return json.load(json_file)
def dump(self, data: dict) -> None:
"""Dumps the dict into the json.
Args:
data (dict): The data to dump.
"""
with open(self.json_path, mode="w") as json_file:
json.dump(data, json_file, indent=4)
def validate(self) -> None:
"""Validates the json if the json is not a valid dict.
"""
try:
with open(self.json_path, mode="r") as json_file:
data = json.load(json_file)
except ValueError:
with open(self.json_path, mode="w") as json_file:
json.dump({}, json_file)
if not isinstance(data, dict):
print("test")
with open(self.json_path, mode="w") as json_file:
json.dump({}, json_file)
class _PathMagic:
@staticmethod @staticmethod
def validate_json(path_to_json): def set(main_dict: dict, path: Union[str, List[str]], *, dump: dict) -> dict:
if not os.path.isfile(path_to_json): """TODO: write description
with open(path_to_json, "w") as json_file:
json.dump({}, json_file)
else:
if os.path.getsize(path_to_json) == 0:
with open(path_to_json, "w") as json_file:
json.dump({}, json_file)
class PathMagic: Args:
main_dict (dict): The dict to modify.
path (Union[str, List[str]]): The path to follow.
dump (dict): The key value pairs to set in the last scope.
@staticmethod Returns:
def set(main_dict: dict, path: str, *, key: str, value): dict: The modified dict.
def magic(alt_dict: dict, key: str): """
if key in alt_dict.keys() and isinstance(alt_dict[key], dict): def magic(alt_dict: dict, key: str) -> dict:
return alt_dict """Validates the key(dict) in the alt_dict.
alt_dict[key] = {}
Args:
alt_dict (dict): The dict to modify.
key (str): The key to validate(dict).
Returns:
dict: The modified dict.
"""
if key in alt_dict.keys() and isinstance(alt_dict[key], dict):
return alt_dict return alt_dict
main_dict_ref, i = main_dict, 0
for dict_name in path.split("+"): alt_dict[key] = {}
return alt_dict
main_dict_ref, i = main_dict, 0
if isinstance(path, str):
path = path.split("+")
for dict_name in path:
i += 1
main_dict = magic(main_dict, dict_name)[dict_name]
if i == len(path):
main_dict.update(dump)
return main_dict_ref
@staticmethod
def get(main_dict: dict, path: Union[str, List[str]], *, key: str, default=None) -> Any:
"""TODO: write description
Args:
main_dict (dict): The dict to get the value of the key in.
path (Union[str, List[str]]): The path to follow.
key (str): The key to get the value of.
default ([type], optional): The value to return if the key is not found. Defaults to None.
Returns:
Any: The value of the key. Will return the default kwarg if the key is not found.
"""
if isinstance(path, str):
path = path.split("+")
for dict_name in path:
try:
main_dict = main_dict[dict_name]
except (KeyError, TypeError, AttributeError):
return default
return main_dict.get(key, default)
@staticmethod
def rem(main_dict: dict, path: Union[str, List[str]], *, key: str) -> dict:
"""TODO: write description
Args:
main_dict (dict): The dict to modify.
path (Union[str, List[str]]):The path to follow.
key (str): The key for the key value pair to remove.
Returns:
dict: The modified dict.
"""
main_dict_ref, i = main_dict, 0
if isinstance(path, str):
path = path.split("+")
for dict_name in path:
try:
i += 1 i += 1
main_dict = magic(main_dict, dict_name)[dict_name] main_dict = main_dict[dict_name]
if i == len(path.split("+")): if i == len(path):
main_dict[key] = value main_dict.pop(key, None)
return main_dict_ref
except (KeyError, TypeError, AttributeError):
@staticmethod return main_dict_ref
def get(main_dict: dict, path: str, *, key, default=None):
for dict_name in path.split("+"): return main_dict_ref
try:
main_dict = main_dict[dict_name]
except (KeyError, TypeError, AttributeError):
return default
return main_dict.get(key, default)
@staticmethod
def rem(main_dict: dict, path: str, *, key):
main_dict_ref, i = main_dict, 0
for dict_name in path.split("+"):
try:
i += 1
main_dict = main_dict[dict_name]
if i == len(path.split("+")):
main_dict.pop(key, None)
except (KeyError, TypeError, AttributeError):
return main_dict_ref
return main_dict_ref
class JsonWrapper: class JsonWrapper:
def __init__(self, path_to_json: str): def __init__(self, json_path: str) -> None:
self.path_to_json = path_to_json self.json_path = json_path
self.utils = Utils self.pathmagic = _PathMagic
self.utils.validate_json(path_to_json) self.json = _JsonUtils(json_path)
self.json.validate()
def set(self, key: str, value, *, pathmagic=""): def set(self, key: str, value, *, pathmagic: Union[str, List[str]] = "") -> None:
self.utils.validate_json(self.path_to_json) """Sets the key value pair in the json. If the pathmagic kwarg is given, (if str)it will split it by the +'s and make dicts inside dicts(or use existing ones) until the list ends. Then it will set the key value pair in the last dict.
with open(self.path_to_json, mode="r") as json_file:
json_data = json.load(json_file)
with open(self.path_to_json, mode="w") as json_file:
if pathmagic == "":
json_data[key] = value
json.dump(json_data, json_file, indent=4)
else:
json.dump(self.utils.PathMagic.set(json_data, pathmagic, key=key, value=value), json_file, indent=4)
def get(self, key: str, *, default=None, pathmagic=""): Args:
self.utils.validate_json(self.path_to_json) key (str): The key for the key value pair.
with open(self.path_to_json, mode="r") as json_file: value ([type]): The value for the key value pair.
json_data = json.load(json_file) pathmagic (Union[str, List[str]], optional): The path to follow. Defaults to "".
if pathmagic == "": """
return json_data.get(key, default) self.json.validate()
else:
return self.utils.PathMagic.get(json_data, pathmagic, key=key, default=default)
def all(self): json_data = self.json.data()
self.utils.validate_json(self.path_to_json)
with open(self.path_to_json, mode="r") as json_file:
return json.load(json_file)
def rem(self, key: str, *, pathmagic=""): if pathmagic == "" or pathmagic == []:
self.utils.validate_json(self.path_to_json) json_data[key] = value
with open(self.path_to_json, mode="r") as json_file: self.json.dump(json_data)
json_data = json.load(json_file)
with open(self.path_to_json, mode="w") as json_file:
if pathmagic == "":
json_data.pop(key, None)
json.dump(json_data, json_file, indent=4)
else:
json.dump(self.utils.PathMagic.rem(json_data, pathmagic, key=key), json_file, indent=4)
def nuke(self): else:
with open(self.path_to_json, mode="w") as json_file: self.json.dump(self.pathmagic.set(
json.dump({}, json_file) json_data, pathmagic, dump={key: value}))
def get(self, key: str, *, default=None, pathmagic: Union[str, List[str]] = "") -> Any:
"""Returns the key's value in the json. Will return the default kwarg if not found. If the pathmagic kwarg is given, (if str)it will split it by the +'s and follow the dicts inside the dicts until the list ends. Then it will return the value of the key in the last dict. The default kwarg applies.
Args:
key (str): The key to get the value of.
default ([type], optional): The value to return if the key is not found. Defaults to None.
pathmagic (Union[str, List[str]], optional): The path to follow. Defaults to "".
Returns:
Any: The value of the key. Will return the default kwarg if the key is not found.
"""
self.json.validate()
json_data = self.json.data()
if pathmagic == "" or pathmagic == []:
return json_data.get(key, default)
return self.pathmagic.get(json_data, pathmagic, key=key, default=default)
def all(self) -> dict: # The same as _JsonUtils.data()
"""Returns all the json data.
Returns:
dict: All the json data.
"""
self.json.validate()
return self.json.data()
def rem(self, key: str, *, pathmagic: Union[str, List[str]] = "") -> None:
"""Removes the key value pair in the json. If the pathmagic kwarg is given, (if str)it will split it by the +'s and follow the dicts inside the dicts until the list ends. Then it will remove the key value pair in the last dict. Does nothing if the key value pair doesn't exist.
Args:
key (str): The key to remove.
pathmagic (Union[str, List[str]], optional): The path to follow. Defaults to "".
"""
self.json.validate()
json_data = self.json.data()
if pathmagic == "" or pathmagic == []:
json_data.pop(key, None)
self.json.dump(json_data)
else:
self.json.dump(self.pathmagic.rem(
json_data, pathmagic, key=key))
def nuke(self, *, pathmagic: Union[str, List[str]] = "") -> None:
"""Nukes the entire database. If the pathmagic kwarg is given, (if str)it will split it by the +'s and follow the dicts inside the dicts until the list ends. Then it will nuke the last dict.
Args:
pathmagic (Union[str, List[str]], optional): The path to follow. Defaults to "".
"""
if pathmagic == "" or pathmagic == []:
self.json.dump({})
return
elif isinstance(pathmagic, str):
pathmagic = pathmagic.split("+")
pm_last = pathmagic.pop()
self.json.dump(self.pathmagic.set(self.json.data(), pathmagic, dump={pm_last: {}}))

View file

@ -6,11 +6,11 @@ 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=long_description,
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.0.2", version="1.1.0",
author="RGBCube", author="RGBCube",
py_modules=["json_wrapper"], py_modules=["json_wrapper"],
license="CC0 1.0 Universal" license="CC0 1.0 Universal"