我正在寻找与Java等效的Dhall,这样我就可以将一些原始的toString嵌入到另一个记录中,但我希望确保得到的JSON结构是有效的。
我有一条记录,例如{ name : Text, age : Natural },并希望将值转换为文本,例如:
let friends =
[ { name = "Bob", age = 25 }, { name = "Alice", age = 24 }]
in { id = "MyFriends", data = Record/toString friends }这将产生以下结果:
{
"id": "MyFriends,
"data": "[ { \"name\": \"Bob\", \"age\": 25 }, { \"name\": \"Alice\", \"age\": 24 }]"
}在Dhall中这是可能的吗?
发布于 2020-02-13 12:00:44
到JSON的转换不能自动派生,但您可以使用Prelude对JSON的支持来生成按构造更正的JSON字符串(这意味着它们永远不会格式错误),如下所示:
let Prelude = https://prelude.dhall-lang.org/v13.0.0/package.dhall
let Friend = { name : Text, age : Natural }
let Friend/ToJSON
: Friend → Prelude.JSON.Type
= λ(friend : Friend)
→ Prelude.JSON.object
( toMap
{ name = Prelude.JSON.string friend.name
, age = Prelude.JSON.natural friend.age
}
)
let Friends/ToJSON
: List Friend → Prelude.JSON.Type
= λ(friends : List Friend)
→ Prelude.JSON.array
(Prelude.List.map Friend Prelude.JSON.Type Friend/ToJSON friends)
let friends = [ { name = "Bob", age = 25 }, { name = "Alice", age = 24 } ]
in { id = "MyFriends", data = Prelude.JSON.render (Friends/ToJSON friends) }这将产生以下结果:
{ data =
"[ { \"age\": 25, \"name\": \"Bob\" }, { \"age\": 24, \"name\": \"Alice\" } ]"
, id = "MyFriends"
}https://stackoverflow.com/questions/60175818
复制相似问题