Question

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?

No correct solution

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top