You can experiment with the correspondence between Daml data types and their JSON equivalent using the :json
directive at the REPL.
For example (look to the following for additional details):
$ daml repl .daml/dist/t-0.0.1.dar --import t
daml> let a = [Album with title = "first title", year = 12, us_peak_chart_post = ""]
daml> :json a
[{"title":"first title","year":12,"us_peak_chart_post":""}]
daml>
Here is a full example of how things fit together, to make things a bit more concrete. Let’s start with daml.yaml
(generated by daml new t
using the Daml SDK version 2.8.1):
# for config file options, refer to
# https://docs.daml.com/tools/assistant.html#project-config-file-daml-yaml
sdk-version: 2.8.1
name: t
source: daml
init-script: Main:setup
version: 0.0.1
dependencies:
- daml-prim
- daml-stdlib
- daml-script
Next, we have daml/Main.daml
(also initially generated by the daml new t
command, but heavily modified):
module Main where
import Daml.Script (script, Script)
import DA.List (head)
data Album = Album with
title : Text
year: Int
us_peak_chart_post : Text
setup : [Album] -> Script ()
setup albums = script do
debug $ "There were " <> show (length albums) <> "albums."
debug $ "The first one was titled: " <> show (title $ head albums) <> "."
Finally, we have an input file albums.json
:
[{"title": "The White Stripes",
"year": 1999,
"us_peak_chart_post": "-"}]
Now, with that, we can run daml build
to create the dar file:
$ daml build
Running single package build of t as no multi-package.yaml was found.
2024-02-15 18:29:41.10 [INFO] [build]
Compiling t to a DAR.
2024-02-15 18:29:41.83 [INFO] [build]
Created .daml/dist/t-0.0.1.dar
$
and, once the dar is created, we can run the above daml repl
command (now that .daml/dist/t-0.0.1.dar
exists), or we can run the script against our input JSON file. However, we first need a running ledger, so, in another terminal but form the same folder:
$ daml sandbox
Starting Canton sandbox.
Listening at port 6865
Canton sandbox is ready.
and, while that’s left running:
$ daml script --ledger-host localhost --ledger-port 6865 --dar .daml/dist/t-0.0.1.dar --script-name Main:setup --input-file albums.json
Slf4jLogger started
[DA.Internal.Prelude:557]: \"There were 1albums.\"
[DA.Internal.Prelude:557]: \"The first one was titled: \\\"The White Stripes\\\".\"
Running CoordinatedShutdown with reason [ActorSystemTerminateReason]
$
You’ll probably want to be doing other things with the data than print it as debug logs, but hopefully this shows you how to tie the pieces together.