Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
JSON
Short JSON Schema
Commits
f46b71f3
Commit
f46b71f3
authored
Oct 18, 2019
by
Paul Warren
Browse files
More documentation and tests.
parent
9ff0bd29
Pipeline
#110
canceled with stages
Changes
2
Pipelines
1
Hide whitespace changes
Inline
Side-by-side
README.md
View file @
f46b71f3
...
...
@@ -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:
...
...
shortjsonschema/tests/test_short_schema.py
View file @
f46b71f3
...
...
@@ -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
:
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment