jsonb 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
jsonb/__init__.py ADDED
@@ -0,0 +1,209 @@
1
+ # coding=utf8
2
+ """JSON Better
3
+
4
+ Wrapper for Python json module which handles custom types
5
+ """
6
+
7
+ __author__ = "Chris Nasr"
8
+ __copyright__ = "Ouroboros Coding Inc."
9
+ __email__ = "chris@ouroboroscoding.com"
10
+ __created__ = "2023-03-15"
11
+
12
+ # Python modules
13
+ import json
14
+ from datetime import datetime
15
+ from decimal import Decimal
16
+ import os
17
+
18
+ def add_class(constructor: callable, callback: callable):
19
+ """Add Class
20
+
21
+ Allows adding a class to be processed by a special callback
22
+
23
+ Arguments
24
+ constructor (type): The class to be processed by the callback
25
+ callback (function): The callback to pass instances of the class
26
+
27
+ Returns:
28
+ None
29
+ """
30
+ __Encoder.add_class(constructor, callback)
31
+
32
+ def decode(s: str, **kwargs):
33
+ """Decode
34
+
35
+ Handles decoding JSON, as a string, into objects/values
36
+
37
+ Args:
38
+ s (str): The JSON to decode
39
+ **kwargs: Additional arguments passed to json.loads. parse_float
40
+ defaults to Decimal if not provided.
41
+
42
+ Returns:
43
+ mixed
44
+ """
45
+ kwargs.setdefault('parse_float', Decimal)
46
+ return json.loads(s, **kwargs)
47
+
48
+ def decodef(f, **kwargs):
49
+ """Decode File
50
+
51
+ Handles decoding JSON, from a file, into objects/values
52
+
53
+ Args:
54
+ f (_io.TextIOWrapper): An instance of a file object with read/write
55
+ methods
56
+ **kwargs: Additional arguments passed to json.load. parse_float
57
+ defaults to Decimal if not provided.
58
+
59
+ Returns:
60
+ mixed
61
+ """
62
+ kwargs.setdefault('parse_float', Decimal)
63
+ return json.load(f, **kwargs)
64
+
65
+ def encode(o: any, indent = None, **kwargs):
66
+ """Encode
67
+
68
+ Handles encoding objects/values into a JSON string
69
+
70
+ Args:
71
+ o (any): The object or value to encode
72
+ indent: Indentation level passed to json.dumps
73
+ **kwargs: Additional arguments passed to json.dumps. cls defaults to
74
+ the jsonb encoder if not provided.
75
+
76
+ Returns:
77
+ str
78
+ """
79
+ kwargs.setdefault('cls', __Encoder)
80
+ if 'indent' not in kwargs:
81
+ kwargs['indent'] = indent
82
+ return json.dumps(o, **kwargs)
83
+
84
+ def encodef(o, f, indent=None, **kwargs):
85
+ """Encode File
86
+
87
+ Handles encoding objects/values into JSON and storing them in the given file
88
+
89
+ Args:
90
+ o (mixed): The object or value to encode
91
+ f (_io.TextIOWrapper): An instance of a file object with read/write
92
+ methods
93
+ indent: Indentation level passed to json.dump
94
+ **kwargs: Additional arguments passed to json.dump. cls defaults to
95
+ the jsonb encoder if not provided.
96
+
97
+ Returns:
98
+ None
99
+ """
100
+ kwargs.setdefault('cls', __Encoder)
101
+ if 'indent' not in kwargs:
102
+ kwargs['indent'] = indent
103
+ return json.dump(o, f, **kwargs)
104
+
105
+ # load function
106
+ def load(filepath, **kwargs):
107
+ """Load
108
+
109
+ Loads a data structure from a JSON file given a full or relative path to it
110
+
111
+ Args:
112
+ filepath (str): The path to the file to load
113
+ **kwargs: Additional arguments passed to decode / json.loads
114
+
115
+ Returns:
116
+ mixed
117
+ """
118
+
119
+ # If ~ is present
120
+ if '~' in filepath:
121
+ filepath = os.path.expanduser(filepath)
122
+
123
+ # Load the file
124
+ with open(filepath, 'r') as oFile:
125
+
126
+ # Convert it to a python variable and return it
127
+ return decode(oFile.read(), **kwargs)
128
+
129
+ # store function
130
+ def store(data, filepath, indent=None, **kwargs):
131
+ """Store
132
+
133
+ Converts an object/value into JSON and stores it in the file path given
134
+
135
+ Args:
136
+ data: The object or value to encode
137
+ filepath (str): The full or relative path to the file
138
+ indent: Indentation level passed to encode / json.dumps
139
+ **kwargs: Additional arguments passed to encode / json.dumps
140
+
141
+ Returns:
142
+ None
143
+ """
144
+
145
+ # If ~ is present
146
+ if '~' in filepath:
147
+ filepath = os.path.expanduser(filepath)
148
+
149
+ # Open a file to write the data
150
+ with open(filepath, 'w') as oFile:
151
+
152
+ # Write the JSON to the file
153
+ oFile.write(encode(data, indent, **kwargs))
154
+
155
+ class __Encoder(json.JSONEncoder):
156
+ """Encoder
157
+
158
+ Handles encoding types the default JSON encoder can't handle
159
+
160
+ """
161
+
162
+ __classes = {
163
+ datetime: lambda x: x.strftime('%Y-%m-%d %H:%M:%S'),
164
+ Decimal: lambda x: '{0:f}'.format(x)
165
+ }
166
+ """Classes
167
+
168
+ Maps types to callbacks used when the default JSON encoder cannot
169
+ handle a value. Lookup walks the instance's MRO so the most specific
170
+ registered type wins."""
171
+
172
+ @classmethod
173
+ def add_class(cls, constructor: callable, callback: callable):
174
+ """Add Class
175
+
176
+ Allows adding a class to be processed by a special callback
177
+
178
+ Arguments
179
+ constructor (type): The class to be processed by the callback
180
+ callback (function): The callback to pass instances of the class
181
+
182
+ Returns:
183
+ None
184
+ """
185
+
186
+ # Register / replace the handler for this exact type
187
+ cls.__classes[constructor] = callback
188
+
189
+ # default method
190
+ def default(self, obj):
191
+ """Default
192
+
193
+ Called when the regular Encoder can't figure out what to do with the
194
+ type
195
+
196
+ Args:
197
+ obj (mixed): An unknown object or value that needs to be encoded
198
+
199
+ Returns:
200
+ str
201
+ """
202
+
203
+ # Walk the MRO so a subclass handler beats a registered parent
204
+ for oClass in type(obj).__mro__:
205
+ if oClass in self.__classes:
206
+ return self.__classes[oClass](obj)
207
+
208
+ # Bubble back up to the parent default
209
+ return json.JSONEncoder.default(self, obj)
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.5
2
+ Name: jsonb
3
+ Version: 1.0.1
4
+ Summary: JSON Better - A Python Library Used to simplify encoding/decoding JSON while handling special types
5
+ Project-URL: Source, https://github.com/ouroboroscoding/jsonb
6
+ Project-URL: Tracker, https://github.com/ouroboroscoding/jsonb/issues
7
+ Author-email: "Chris Nasr - Ouroboros Coding Inc." <chris@ouroboroscoding.com>
8
+ Maintainer-email: "Chris Nasr - Ouroboros Coding Inc." <chris@ouroboroscoding.com>
9
+ License-File: LICENSE
10
+ Keywords: json
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+
14
+ # JSON Better
15
+ [![pypi version](https://img.shields.io/pypi/v/jsonb.svg)](https://pypi.org/project/jsonb)
16
+ ![MIT License](https://img.shields.io/pypi/l/jsonb.svg)
17
+
18
+ A Python library used to simplify encoding/decoding JSON while handling special
19
+ types such as `Decimal` and `datetime`.
20
+
21
+ Please see [LICENSE](https://github.com/ouroboroscoding/jsonb/blob/main/LICENSE)
22
+ for further information.
23
+
24
+ See [Releases](https://github.com/ouroboroscoding/jsonb/blob/main/releases.md)
25
+ for changes from release to release.
26
+
27
+ ## Requires
28
+ jsonb requires python 3.10 or higher
29
+
30
+ ## Installation
31
+ ```bash
32
+ pip install jsonb
33
+ ```
34
+
35
+ ## Usage
36
+
37
+ ```python
38
+ import jsonb
39
+ from decimal import Decimal
40
+ from datetime import datetime
41
+
42
+ # Encode special types
43
+ s = jsonb.encode({
44
+ 'amount': Decimal('12.50'),
45
+ 'when': datetime(2023, 3, 15, 12, 0, 0)
46
+ })
47
+
48
+ # Decode floats as Decimal by default
49
+ data = jsonb.decode('{"amount": 12.50}')
50
+ # data['amount'] is Decimal('12.5')
51
+
52
+ # Pass additional arguments through to the json module
53
+ s = jsonb.encode(data, indent=2, sort_keys=True)
54
+ data = jsonb.decode(s, parse_int=Decimal)
55
+ ```
56
+
57
+ ### File helpers
58
+
59
+ ```python
60
+ import jsonb
61
+
62
+ # Load / store by path (~ is expanded)
63
+ data = jsonb.load('~/config.json')
64
+ jsonb.store(data, '~/config.json', indent=2)
65
+
66
+ # Or work with open file objects
67
+ with open('data.json', 'r') as f:
68
+ data = jsonb.decodef(f)
69
+
70
+ with open('data.json', 'w') as f:
71
+ jsonb.encodef(data, f, indent=2)
72
+ ```
73
+
74
+ ### Custom types
75
+
76
+ ```python
77
+ import jsonb
78
+
79
+ class Point:
80
+ def __init__(self, x, y):
81
+ self.x = x
82
+ self.y = y
83
+
84
+ jsonb.add_class(Point, lambda p: {'x': p.x, 'y': p.y})
85
+ print(jsonb.encode(Point(1, 2)))
86
+ ```
@@ -0,0 +1,5 @@
1
+ jsonb/__init__.py,sha256=hNVSPnDc26RF3u87UZkBDjTt143EekqXbsbPlbm5kSY,4910
2
+ jsonb-1.0.1.dist-info/METADATA,sha256=jxHt1wwhOctVjtTStQj39vYYpyYaa3vwrSr-w1ZX0iE,2161
3
+ jsonb-1.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
4
+ jsonb-1.0.1.dist-info/licenses/LICENSE,sha256=5RMNwznBsSdPwWKL2usG73FA0_6m1HSRW0DHY3N0gzI,1077
5
+ jsonb-1.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ouroboros Coding Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.