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?
代数数据类型是准确描述数据的便捷方式。 JSON中的产品类型没有问题。但是,不清楚sum-type是什么,所以如何在JSON中表示变体类型?
2 个解决方案
#1
3
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.
对象和特殊格式的字符串基本上是您在JSON中自描述数据类型的唯一实际选项。
#2
3
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.
在JSON中,您可以使用以下三种形式来指定三种变体。
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.
基本上,使用具有单个键值对的JSON对象,其中键是选定的变体。
#1
3
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.
对象和特殊格式的字符串基本上是您在JSON中自描述数据类型的唯一实际选项。
#2
3
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.
在JSON中,您可以使用以下三种形式来指定三种变体。
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.
基本上,使用具有单个键值对的JSON对象,其中键是选定的变体。