Metadata-Version: 2.4
Name: jsxn
Version: 0.4
Summary: Slotted Python classes generated from example JSON objects
Author-email: Matthew Shaw <mshaw.cx@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/shawcx/jsxn
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

jsxn
====

jsxn is a Python library for JSON objects that use a strict schema. Designed
for use with REST APIs that return lists of objects that all have the same
attributes.

The jsxn object will programmatically generate a Python class based on a JSON
string, Python dictionary, keyword arguments, or an iterable collection of
attribute names.

```python
from jsxn import jsxn

# this will create a jsxn class 'dynamic' that has 'schema' and 'key' as attributes
instance = jsxn.dynamic({'schema':100,'key':'value'})

# str representations of jsxn instances will be JSON
print(instance)
# {"schema": 100, "key": "value"}

# jsxn instances can be passed to dict
print(dict(instance))
# {'schema': 100, 'key': 'value'}

# repr shows the class name and the values
print(repr(instance))
# dynamic(schema=100, key='value')

# instances of the same class with the same values are equal
print(instance == jsxn.dynamic(schema=100, key='value'))
# True

# future references of the class will use the generated class
another = jsxn.dynamic('{"schema":200,"key":"something"}')

# previously generated classes can be called without arguments
builder = jsxn.dynamic()
print(builder)
# {"schema": null, "key": null}

# attributes can be accessed directly
builder.schema = 300
# or by indices
builder['key'] = 'populate'
print(builder)
# {"schema": 300, "key": "populate"}

# and fields can be checked for by name
print('key' in builder)
# True

# jsxn instances are callable with JSON strings
builder('{"schema":500}')
# and keywords
builder(key='hello')
print(builder)
# {"schema": 500, "key": "hello"}

# a dict or JSON string can be combined with keywords, which are applied last
builder({'schema':600,'key':'replaced'}, key='world')
print(builder)
# {"schema": 600, "key": "world"}

# jsxn objects use slots so only attributes defined at creation can be assigned
try:
    builder.not_defined = True
except AttributeError as e:
    print(e)
    # 'dynamic' object has no attribute 'not_defined'

# delete a jsxn class in order to reuse it
del jsxn.dynamic

# a jsxn class can be defined with a list of keys
instance = jsxn.dynamic(['attr1','attr2','attr3'])
# all the variables will be uninitialized
print(instance)
# {"attr1": null, "attr2": null, "attr3": null}

# jsxn classes can also be deleted by indices
del jsxn['dynamic']

# it is possible to create a jsxn class that accept nothing
empty = jsxn.empty()
print(empty)
# {}
# but it is not very useful...
```

Classes can define the names of the fields via annotations or slots. A value
assigned to an annotated field is its default, otherwise fields default to null.

```python
from jsxn import jsxn

@jsxn
class example1:
    first  : str
    second : int = 2
    third  : dict

print(jsxn.example1(first='one'))
# {"first": "one", "second": 2, "third": null}

@jsxn
class example2:
    __slots__ = [
        'first',
        'second',
        'third',
        ]
```

jsxn supports binding classes to generated types. This allows the creation of
helper functions to perform actions with the underlying data.

```python
from jsxn import jsxn

@jsxn
class domain:
    name : str
    def save(self):
        print('SAVE:', self)

d = jsxn.domain({'name':'www.example.com'})
d.save()

@jsxn('computer')
class MachineClass:
    cpu   : str
    cores : int
    ram   : int
    addr  : str
    def ping(self):
        print('PING:', self.addr)

c = jsxn.computer(cpu='x86_64',cores=8,ram=8192,addr='192.168.1.1')
c.ping()
```

Decorated classes can be subclassed. A subclass inherits the fields and the
methods of its parents.

```python
from jsxn import jsxn

@jsxn
class base:
    id : int
    def describe(self):
        return f'{type(self).__name__} #{self.id}'

@jsxn
class user(base):
    name : str

u = jsxn.user(id=1, name='alice')
print(u)
# {"id": 1, "name": "alice"}
print(u.describe())
# user #1
```

Decorating a class with the name of an existing jsxn class adds its methods to
that class. The fields of the existing class are kept.

```python
from jsxn import jsxn

jsxn.host({'addr':'10.0.0.1'})

@jsxn('host')
class HostHelpers:
    def ping(self):
        print('PING:', self.addr)

jsxn.host(addr='10.0.0.2').ping()
# PING: 10.0.0.2
```

jsxn instances can be pickled. Unpickling looks the class up by name, so it
must already be defined in the process that loads the data.
