How do I represent options (types of sums) in JSON?

Algebraic data types are a convenient way to accurately describe data. JSON has no problem with product types. However, it is unclear what type of amount can be, so how can I represent the type of option in JSON ?

+4
source share
2 answers

Perhaps using object notation with parameters valueand tag? For instance:.

{
    "someVariant": {
        "value": 25,
        "tag":   "currentFormOfTheVariant"
    }
}

Object and specially formatted strings are basically your only real options for self-describing data types in JSON.

+3
source

Take, for example, the following type of option.

data Tree = Empty
          | Leaf Int
          | Node Tree Tree

JSON , .

Variant | JSON
--------+---------------
Empty   | null
--------+---------------
Leaf    | {
        |   "leaf": 7
        | }
--------+---------------
Node    | {
        |   "node": [
        |     <tree>,
        |     <tree>
        |   ]
        | }

, JSON -, .

+3

Source: https://habr.com/ru/post/1529859/


All Articles