Algebraic data types are the convenient way to accurately describe the data. There is no problem with product-types in JSON. However it's not clear what a sum-type can be, so how can I represent a variant type in JSON?
In computer science, a sum type, is a data structure used to hold a value that could take on several different, but fixed, types. In practical terms, a Sum Type can be thought of as an enum, with a payload (where that payload is data).
The Either type is the canonical sum type from which we can build all other sum types. In fact, computer scientists often use (+) to refer to Either .
adt is a library providing algebraic data types in Python, with a clean, intuitive syntax, and support for typing through a mypy plugin.
The product type in Scala are typically represented in Scala as a case class or case object or a TupleN instance. They simply contain a fixed order of fields that are associated with logical conjunctions (ANDs).
Take for example the following variant type.
data Tree = Empty
| Leaf Int
| Node Tree Tree
In JSON you can use the following three forms to specify the three variants.
Variant | JSON
--------+---------------
Empty | null
--------+---------------
Leaf | {
| "leaf": 7
| }
--------+---------------
Node | {
| "node": [
| <tree>,
| <tree>
| ]
| }
Basically, use a JSON object with a single key-value pair, where the key is the selected variant.
Perhaps using object notation with value
and tag
properties? E.g.:
{
"someVariant": {
"value": 25,
"tag": "currentFormOfTheVariant"
}
}
Object and specially-formatted strings are basically your only real options for self-describing data types in JSON.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With