-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsonp.py
More file actions
154 lines (127 loc) · 4.42 KB
/
jsonp.py
File metadata and controls
154 lines (127 loc) · 4.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# ModLibrary, a Minecraft mod manager
# Copyright (C) 2024 iamliuzy
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Contact the author: iamliuzy <liuzhiyu.sh@outlook.com>
from pathlib import Path
from json import loads, dumps
from typing import Any
import jsons
class JsonFile:
"""
Provide access for a JSON file.
"""
def __init__(self, path: str, filetype: str = "") -> None:
"""
Create a new JsonFile instance.
:param path: Path to the JSON file.
:param filetype: Type of the JSON file.
:raises TypeError: If the filetype is not specified and cannot be
determined.
:raises json.JSONDecodeError: If the JSON file contains invalid data.
"""
self.path = Path(path)
with open(self.path, "r", encoding="utf-8") as file:
text = file.read()
if filetype == "":
try:
self.obj = loads(text)
except ValueError:
raise TypeError(f"Cannot determine the JSON file type: {self.
path}")
elif filetype == "list":
self.obj = list(loads(text))
elif filetype == "dict":
self.obj = dict(loads(text))
else:
raise ValueError(f"Unknown JSON file type: {filetype}")
def get(self) -> dict | list:
"""
Get the JSON data.
:return: The JSON data.
"""
return self.obj
def store(self, new: dict | list) -> None:
"""
Store the JSON data.
:param new: The new JSON data.
"""
with open(self.path, mode="w", encoding="utf-8") as file:
file.write(dumps(new))
def qread(path: str, encoding='utf-8') -> str:
"""Shortcut to read a file.
:param path: The file to read
:type path: str
:param encoding: The encoding, defaults to 'utf-8'
:type encoding: str, optional
:return: The content of the file
:rtype: str
"""
with open(Path(path), encoding=encoding, mode='r') as f:
return f.read()
def json_to_dict(path) -> dict:
"""
Read json file and return the content.
"""
return dict(JsonFile(path, "dict").get())
def json_to_list(path) -> list:
"""
Read json file and return the content.
"""
return list(JsonFile(path, "list").get())
def jsonfile_to_obj(path: str, cls: type) -> Any:
"""Get json content as object using `jsons`
:param path: Path to the json file
:type path: str
:param cls: Content type of the json file
:type cls: type
:return: An instance of `cls` that initialized with json content
:rtype: cls
"""
r = qread(path)
if issubclass(cls, jsons.JsonSerializable):
return cls.loads(r)
else:
return jsons.loads(r, cls)
def obj_to_json(obj: Any) -> str:
"""Serialize an object to json string using `jsons`
:param obj: The object to serialize
:type obj: Any
:return: The serialized json string.
:rtype: str
"""
if isinstance(obj, jsons.JsonSerializable):
return obj.dumps()
else:
return jsons.dumps(obj)
def obj_to_jsonfile(obj: Any, path: str) -> None:
"""Serialize an object to json string using `jsons`
:param obj: The object to serialize
:type obj: Any
:return: The serialized json string.
:rtype: str
"""
with open(Path(path), encoding='utf-8', mode='w') as f:
f.write(obj_to_json(obj))
def manifest_to_dict(path):
result = {}
with open(Path(path), mode="r", encoding="utf-8") as file:
for line in map(str.strip, file.readlines()):
if not (":" in line):
continue
key, value = line.split(":", maxsplit=1)
result[key] = value.strip()
return result