Daml Template Data conversion to JSON data

I just want to ask if there’s a function that converts Daml template data to Json format. I have these code for example :

template Log with 
    message : Text
    owner : Party 
  where signatory owner
templtate OtherData with 
   data1 : Text
   data2 : Text
   .. -- more data
-- assume variable od is a data from OtherData
create Log with
   message = show od

In the UI, the field message is a text format, but It’s a bit complicated to parse it to JSON Object as the show function gives a different format data.

Is there a way or tool I can used to convert od into JSON format data, instead of show?


1 Like

daml repl has a :json command, e.g.,

daml> :json (1,2)

At the moment you cannot access it within your Daml code though or from client libraries.

Ok, so the solution is not to use show and format it properly so that JSON.parse it properly.


One way to print a JSON with the contract payload is the following:

  1. Create a choice on the contract which returns the payload (not the contract id which we usually need).
  2. Start Sandbox and create a contract instance.
  3. Exercise the choice with Postman, the API call will return the contract payload (the return value of the choice) in JSON format. (Alternatively, you can create a Daml Script which exercises the choice, and run the Daml Script with the daml script command, specifying a filename with the --output-file option. The command will print the JSON into this file.)

The choice mentioned in #1 is like the PrintPayload choice on the following template:

type AssetId = ContractId Asset

template Asset
    issuer : Party
    owner  : Party
    name   : Text
    ensure name /= ""
    signatory issuer
    observer owner
    choice Give : AssetId
        newOwner : Party
      controller owner
      do create this with
           owner = newOwner
    nonconsuming choice PrintPayload : Asset
      controller owner
      do return this

If you don’t want to write an extra choice for this, you can also use the queryContractId command to retrieve the contract payload after creating the contract in the same Daml Script:

setup : Script Asset
setup = script do
  alice <- allocatePartyWithHint "Alice" (PartyIdHint "Alice")

  aliceTV <- submit alice do
    createCmd Asset with
      issuer = alice
      owner = alice
      name = "TV"

  Some asset <- queryContractId alice aliceTV
  return asset
1 Like