Search code examples
dhall

Dhall Record to Text


I'm looking for the Dhall equivalent of Java's toString so I can embed some raw JSON inside another record, but I wish to ensure the resulting JSON structure is valid.

I have a Record, e.g. { name : Text, age : Natural } and wish to convert a value to Text, e.g.:

let friends = 
[ { name = "Bob", age = 25 }, { name = "Alice", age = 24 }]
in { id = "MyFriends", data = Record/toString friends }

which would produce:

{
  "id": "MyFriends, 
  "data": "[ { \"name\": \"Bob\", \"age\": 25 }, { \"name\": \"Alice\", \"age\": 24 }]" 
}

Is this possible in Dhall?


Solution

  • The transformation to JSON can't be derived automatically, but you can use the Prelude's support for JSON to generate correct-by-construction JSON strings (meaning that they will never be malformed), like this:

    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) }
    

    That produces the following result:

    { data =
        "[ { \"age\": 25, \"name\": \"Bob\" }, { \"age\": 24, \"name\": \"Alice\" } ]"
    , id = "MyFriends"
    }