如何在 JSON 中表示变体(和类型)?

Tri*_*Gao 8 json functional-programming variant

代数数据类型是准确描述数据的便捷方式。JSON 中的产品类型没有问题。但是,尚不清楚 sum-type 可以是什么,那么如何在 JSON 中表示变体类型

Tim*_*lds 8

以以下变体类型为例。

data Tree = Empty
          | Leaf Int
          | Node Tree Tree
Run Code Online (Sandbox Code Playgroud)

在 JSON 中,您可以使用以下三种形式来指定三种变体。

Variant | JSON
--------+---------------
Empty   | null
--------+---------------
Leaf    | {
        |   "leaf": 7
        | }
--------+---------------
Node    | {
        |   "node": [
        |     <tree>,
        |     <tree>
        |   ]
        | }
Run Code Online (Sandbox Code Playgroud)

基本上,使用具有单个键值对的 JSON 对象,其中键是选定的变体。

  • 漂亮的 ASCII 图形:) (2认同)

T.J*_*der 6

也许使用带有valuetag属性的对象表示法?例如:

{
    "someVariant": {
        "value": 25,
        "tag":   "currentFormOfTheVariant"
    }
}
Run Code Online (Sandbox Code Playgroud)

对象和特殊格式的字符串基本上是 JSON 中自描述数据类型的唯一真正选择。