echidnae-json 0.1.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.
@@ -0,0 +1,29 @@
1
+ """Parse JSON into dictionaries with JavaScript-style attribute access."""
2
+
3
+ from json import JSONDecodeError
4
+
5
+ from ._parser import JSONObject, JSONValue, dumps, load, loads, parse, stringify
6
+
7
+ __all__ = [
8
+ "JSONDecodeError",
9
+ "JSONObject",
10
+ "JSONValue",
11
+ "dumps",
12
+ "load",
13
+ "loads",
14
+ "parse",
15
+ "stringify",
16
+ ]
17
+
18
+
19
+ class JSON:
20
+ """JSON operations with Python values and attribute-access dictionaries."""
21
+
22
+ parse = staticmethod(parse)
23
+ loads = staticmethod(loads)
24
+ load = staticmethod(load)
25
+ dumps = staticmethod(dumps)
26
+ stringify = staticmethod(stringify)
27
+
28
+
29
+ __all__.append("JSON")
@@ -0,0 +1,105 @@
1
+ """Decode and encode JSON with attribute access for object properties."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json as _json
6
+ from typing import Any, BinaryIO, Never, TextIO
7
+
8
+
9
+ def _is_special_attribute(name: str) -> bool:
10
+ return name.startswith("__") and name.endswith("__")
11
+
12
+
13
+ class JSONObject(dict[str, Any]):
14
+ """A dictionary whose JSON keys also support attribute access.
15
+
16
+ JSON keys take precedence over ordinary dictionary attributes. Special
17
+ Python attributes keep their normal meaning; use brackets for those keys.
18
+ Attribute assignment and deletion operate on the dictionary itself.
19
+ """
20
+
21
+ __slots__ = ()
22
+
23
+ def __getattribute__(self, name: str) -> Any:
24
+ if not _is_special_attribute(name) and dict.__contains__(self, name):
25
+ return dict.__getitem__(self, name)
26
+ return dict.__getattribute__(self, name)
27
+
28
+ def __setattr__(self, name: str, value: Any) -> None:
29
+ if _is_special_attribute(name):
30
+ raise AttributeError(f"Use brackets to assign JSON key {name!r}")
31
+ dict.__setitem__(self, name, value)
32
+
33
+ def __delattr__(self, name: str) -> None:
34
+ if _is_special_attribute(name):
35
+ raise AttributeError(f"Use brackets to delete JSON key {name!r}")
36
+ try:
37
+ dict.__delitem__(self, name)
38
+ except KeyError:
39
+ raise AttributeError(f"No JSON key named {name!r}") from None
40
+
41
+
42
+ type JSONValue = JSONObject | list[JSONValue] | str | int | float | bool | None
43
+
44
+
45
+ def _reject_constant(value: str) -> Never:
46
+ raise ValueError(f"{value} is not a valid JSON numeric constant")
47
+
48
+
49
+ def parse(source: str | bytes | bytearray) -> JSONValue:
50
+ """Parse JSON text, converting every object to a :class:`JSONObject`.
51
+
52
+ Arrays remain lists; strings, numbers, booleans, and null become native
53
+ Python values. Syntax errors raise ``json.JSONDecodeError``. Nonstandard
54
+ constants such as ``NaN`` and ``Infinity`` raise ``ValueError``.
55
+ """
56
+ return _json.loads(
57
+ source,
58
+ object_hook=JSONObject,
59
+ parse_constant=_reject_constant,
60
+ )
61
+
62
+
63
+ loads = parse
64
+
65
+
66
+ def load(source: TextIO | BinaryIO) -> JSONValue:
67
+ """Read and parse a JSON document from an open text or binary file."""
68
+ return parse(source.read())
69
+
70
+
71
+ def _plain_containers(value: object, memo: dict[int, Any]) -> Any:
72
+ """Remove attribute access without losing shared or circular references."""
73
+ if isinstance(value, (dict, list, tuple)):
74
+ identity = id(value)
75
+ if identity in memo:
76
+ return memo[identity]
77
+ if isinstance(value, dict):
78
+ result: dict[Any, Any] = {}
79
+ memo[identity] = result
80
+ for key, child in dict.items(value):
81
+ result[key] = _plain_containers(child, memo)
82
+ return result
83
+ sequence: list[Any] = []
84
+ memo[identity] = sequence
85
+ sequence.extend(_plain_containers(child, memo) for child in value)
86
+ return sequence
87
+ return value
88
+
89
+
90
+ def stringify(
91
+ value: object,
92
+ *,
93
+ indent: int | str | None = None,
94
+ ensure_ascii: bool = True,
95
+ ) -> str:
96
+ """Serialize JSON-compatible values, including keys that shadow methods."""
97
+ return _json.dumps(
98
+ _plain_containers(value, {}),
99
+ indent=indent,
100
+ ensure_ascii=ensure_ascii,
101
+ allow_nan=False,
102
+ )
103
+
104
+
105
+ dumps = stringify
@@ -0,0 +1,160 @@
1
+ Metadata-Version: 2.4
2
+ Name: echidnae-json
3
+ Version: 0.1.1
4
+ Summary: JSON parsing, serialization and JavaScript-style object traversal
5
+ Author: ellainng
6
+ Author-email: ellainng <299958882+ellainng@users.noreply.github.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE.md
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Programming Language :: Python :: 3.14
11
+ Requires-Python: >=3.14
12
+ Project-URL: Repository, https://github.com/wispsy/echidnae
13
+ Project-URL: Issues, https://github.com/wispsy/echidnae/issues
14
+ Description-Content-Type: text/markdown
15
+
16
+ # echidnae-json
17
+
18
+ Parse JSON in Python and traverse its objects with JavaScript-style dot access:
19
+
20
+ ```python
21
+ import echidnae.json as JSON
22
+
23
+ obj = JSON.parse('[{"key": {"value": "hello"}}]')
24
+
25
+ assert obj[0].key.value == "hello"
26
+ assert obj[0]["key"]["value"] == "hello"
27
+ ```
28
+
29
+ Requires Python 3.14 or later and has no runtime dependencies. The import is `echidnae.json`; Python's standard-library `json` remains available. The distribution
30
+ name is `echidnae-json`.
31
+
32
+ ## Install
33
+
34
+ ```sh
35
+ python -m pip install echidnae-json
36
+ ```
37
+
38
+ Use `from echidnae.json import JSON` for the facade, or `import echidnae.json as JSON` for the module API.
39
+
40
+ ## Installation and tests
41
+
42
+ From the project directory:
43
+
44
+ ```sh
45
+ uv sync
46
+ uv run python -m unittest discover -s tests -v
47
+ uv build
48
+ ```
49
+
50
+ Alternatively, install with `python -m pip install -e .` and run
51
+ `python -m unittest discover -s tests -v` in that environment.
52
+
53
+ ## How it works
54
+
55
+ `parse()` uses Python's standard `json` decoder with an object hook. Every JSON
56
+ object, including objects nested inside arrays, becomes a `JSONObject`, which is
57
+ a `dict` subclass. Arrays remain ordinary lists and scalar values remain native
58
+ Python values.
59
+
60
+ ```python
61
+ data = JSON.loads('''{
62
+ "users": [
63
+ {"name": "Ada", "profile": {"active": true}},
64
+ {"name": "Lin", "profile": {"active": false}}
65
+ ],
66
+ "next": null
67
+ }''')
68
+
69
+ assert data.users[0].profile.active is True
70
+ assert data.next is None
71
+ assert [user.name for user in data.users] == ["Ada", "Lin"]
72
+ assert len(data.users) == 2
73
+ ```
74
+
75
+ | JSON value | Python value |
76
+ | --- | --- |
77
+ | Object | `JSONObject` (`dict` subclass) |
78
+ | Array | `list` |
79
+ | String | `str` |
80
+ | Integer / fractional number | `int` / `float` |
81
+ | `true` / `false` | `True` / `False` |
82
+ | `null` | `None` |
83
+
84
+ This provides JavaScript-style object traversal within Python. Use Python's
85
+ `len()`, loops, and list operations; indices, slicing, and negative indices follow
86
+ Python's rules. Top-level arrays and scalar JSON documents are supported too.
87
+
88
+ ## Keys, dictionary methods, and mutation
89
+
90
+ Use brackets for keys containing spaces or punctuation, Python keywords, and
91
+ special Python attribute names such as `__class__`:
92
+
93
+ ```python
94
+ data = JSON.parse('''{
95
+ "display-name": "Ada",
96
+ "class": "example",
97
+ "items": [{"value": 7}],
98
+ "__class__": "stored value"
99
+ }''')
100
+
101
+ assert data["display-name"] == "Ada"
102
+ assert data["class"] == "example"
103
+ assert data.items[0].value == 7
104
+ assert data["__class__"] == "stored value"
105
+ assert data.__class__ is JSON.JSONObject
106
+ ```
107
+
108
+ JSON keys take precedence over ordinary dictionary attributes, so an `items` key
109
+ is available as `data.items`. Call dictionary methods through the class if a key
110
+ shadows them: `dict.items(data)`, `dict.keys(data)`, or `dict.get(data, "missing")`.
111
+ Otherwise the usual dictionary methods are available directly.
112
+
113
+ Attribute assignment and deletion update the dictionary:
114
+
115
+ ```python
116
+ data = JSON.parse('{"profile": {"name": "Ada"}}')
117
+ data.profile.name = "Grace"
118
+ assert data["profile"]["name"] == "Grace"
119
+
120
+ data.profile.active = True
121
+ del data.profile.active
122
+ assert "active" not in data.profile
123
+ ```
124
+
125
+ Values added after parsing retain their Python types. Inserting a plain `dict`
126
+ does not convert it to a `JSONObject`; use brackets to traverse it, or parse the
127
+ new JSON value before inserting it. Special Python attributes are protected from
128
+ attribute assignment and deletion; their JSON keys can still be changed through
129
+ brackets.
130
+
131
+ ## API and errors
132
+
133
+ | Function | Behavior |
134
+ | --- | --- |
135
+ | `JSON.parse(text)` | Parse `str`, `bytes`, or `bytearray` JSON input. |
136
+ | `JSON.loads(text)` | Alias for `parse()`. |
137
+ | `JSON.load(file)` | Read and parse an open text or binary file. |
138
+ | `JSON.stringify(value, *, indent=None, ensure_ascii=True)` | Serialize parsed objects or ordinary JSON-compatible Python values. |
139
+ | `JSON.dumps(value, **options)` | Alias for `stringify()` with the same supported options. |
140
+
141
+ ```python
142
+ with open("example.json", encoding="utf-8") as source:
143
+ data = JSON.load(source)
144
+
145
+ text = JSON.stringify(data, indent=2, ensure_ascii=False)
146
+ assert JSON.parse(text) == data
147
+ ```
148
+
149
+ Missing dot attributes raise `AttributeError`; missing bracket keys raise
150
+ `KeyError`. Array indices out of range raise `IndexError`. Names inherited from
151
+ `dict` still resolve to dictionary attributes when there is no matching JSON key.
152
+ Malformed JSON raises `JSON.JSONDecodeError` (the same exception class as
153
+ `json.JSONDecodeError`). `NaN`, `Infinity`, and `-Infinity` are rejected with
154
+ `ValueError`. Invalid input types raise `TypeError`.
155
+
156
+ Serialization follows `json.dumps` formatting and Unicode escaping, rejects
157
+ non-finite numbers with `ValueError`, and rejects unsupported Python objects
158
+ with `TypeError`. Use `JSON.stringify()` or `JSON.dumps()` to serialize parsed
159
+ objects: they convert containers to plain dictionaries and lists before
160
+ encoding, so JSON keys such as `items` do not interfere with the encoder.
@@ -0,0 +1,6 @@
1
+ echidnae/json/__init__.py,sha256=8y-4_4lNyIFPK8IATpblt9zAwRiDyWZSE2rDh5lZlCE,618
2
+ echidnae/json/_parser.py,sha256=ctANiJabbf8bieGtcJfR8zAd-EDtl4cLSmPeem0fBDo,3353
3
+ echidnae_json-0.1.1.dist-info/licenses/LICENSE.md,sha256=dJjxPlUliHO6iuJiKxsIn0HSnRRb-dp_8lpVtAunRj8,1063
4
+ echidnae_json-0.1.1.dist-info/WHEEL,sha256=e4_1dyBeezi8ZjfxrZ3bnVOxFDa3ksqVqH0jTHkUZ3k,81
5
+ echidnae_json-0.1.1.dist-info/METADATA,sha256=LznfsPP5_cJ-ayDSgJOt55qScG389fBxzjxFcPzOWvY,5458
6
+ echidnae_json-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.12.19
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 wispsy
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.