Commit f46b71f3 authored by Paul Warren's avatar Paul Warren

More documentation and tests.

parent 9ff0bd29
Pipeline #110 canceled with stages
......@@ -45,6 +45,55 @@ In Short JSON Schema, this becomes:
[jsonschema]: http://json-schema.org/
## Motivation
When writing code that consumes JSON, you should be defensive against JSON that
doesn't match your expectations. Most languages make it easy to defend against
properties that may or may not be present. For example:
```python
someJSON.get("thing", {}).get("subThing", None)
if subThing is not None:
...
```
What is less easy is guarding against properties being present with the wrong type. For example:
```python
json.loads('{"thing": [ ] }').get("thing", {}).get("subThing", None)
```
Gives:
```
AttributeError: 'list' object has no attribute 'get'
```
JSON Schema is a great way to specify declaratively the structure that you
expect, but in its standard syntax, it's often more verbose and barely more
readable than doing type checks manually in code.
Short JSON Schema is intended to allow concise specification of JSON formats,
so that your code needn't be cluttered with checks for the correct structure.
## Defaults
In Short JSON Schema, properties are required by default, and additional
properties are disallowed. Properties can be made optional by adding a `?`
modifier, and additional properties can be allowed by adding `...` in the
property list.
```
{
myString?:$,
...
}
```
All properties allowed, but if present, `myString` must be a string.
## Examples
An object with a single, mandatory string property:
......
......@@ -219,6 +219,35 @@ def test_short_schema():
{ "athing": 123 },
]
},
# different types
{
"input": """
{
nullThing?:~, -- nullable
booleanThing?:B, -- boolean
}
""",
"output": {
"type": "object",
"properties": {
"nullThing": {
"type": "null",
},
"booleanThing": {
"type": "boolean",
}
},
"additionalProperties": False
},
"valid_instances": [
{ "nullThing": None, "booleanThing": True },
],
"invalid_instances": [
{ "nullThing": False, "booleanThing": True },
{ "nullThing": False, "booleanThing": None },
]
},
]
for t in tests:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment