1

我正在寻找 Java 的 Dhall 等价物,toString因此我可以在另一条记录中嵌入一些原始 JSON,但我希望确保生成的 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 这可能吗?

4

1 回答 1

2

无法自动导出到 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"
}
于 2020-02-13T04:00:44.113 回答