Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I represent variants (sum-types) in JSON?

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?

like image 836
Trident D'Gao Avatar asked Mar 03 '14 18:03

Trident D'Gao


People also ask

What is sum data type?

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).

Is either a sum type?

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 .

Does Python have algebraic data types?

adt is a library providing algebraic data types in Python, with a clean, intuitive syntax, and support for typing through a mypy plugin.

What is product type in Scala?

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).


2 Answers

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.

like image 75
Timothy Shields Avatar answered Oct 20 '22 09:10

Timothy Shields


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.

like image 4
T.J. Crowder Avatar answered Oct 20 '22 07:10

T.J. Crowder