Data Objects

A data object is a python class annotated with @jo.data. All data objects are automatically associated with a json schema based on the properties of the class. The associated json schema is used for validation.

Define data objects

import json
from typing import Iterable, List

import justobjects as jo


@jo.data()
class Model:
    a = jo.integer(minimum=3, maximum=30, multiple_of=3)
    b = jo.numeric(default=0.3, multiple_of=2)
    c = jo.string(default="123")


# display schema
print(json.dumps(jo.show_schema(Model), indent=2))

This will output

{
  "type": "object",
  "title": "Draft7 JustObjects schema for data object '__main__.Model'",
  "additionalProperties": false,
  "properties": {
    "$schema": {
      "type": "string",
      "default": "http://json-schema.org/draft-07/schema#"
    },
    "a": {
      "type": "integer",
      "maximum": 30,
      "minimum": 3,
      "multipleOf": 3
    },
    "b": {
      "type": "number",
      "default": 0.3,
      "multipleOf": 2
    },
    "c": {
      "type": "string",
      "default": "123"
    }
  }
}

Validate Instances

Validation can be performed on model instances like this


try:
    # fails validation
    Model(a=3.1415, b=2.72, c="123")
except jo.ValidationException as err:
    print(err.errors)

validation can also be performed on dictionary instances too

try:
    # fails validation
    jo.validate(Model, dict(a=3.1415, b=2.72, c="123"))
except jo.ValidationException as err:
    print(err.errors)

Object Fields

Class fields can be defined using either of the following:

  • PEP-526 annotations on Python 3.6+

  • type arguments using jo field types

PEP 526 fields definitions

typed=True flag can be used to signify the model properties are defined using type annotations.

Note

Type annotations can only be used for basic constraint definitions. For example they cannot be used to defined custom constraints on string fields like maxLenght or pattern. For these the provided custom field types are more suitable.


@jo.data(typed=True)
class TypedModel:
    a: int
    b: float = 0.3
    c: str = "123"