Introduction
It may be necessary to include nested data as an encoded string, such as a bit
of YAML embedded as a string inside a JSON request. The steps below show how to
accomplish that with the cue command line. First with JSON, then with YAML.
Prerequisites
- You have CUE installed
locally. This allows you to run
cuecommands
Encoding Nested JSON
Create a CUE file which uses the json package to encode an inner value:
nested-json.cue
import "encoding/json"
_innerData: {
innerString: "inside"
}
nestedJSON: json.Marshal(_innerData)
outerString: "outside"Use cue export to evaluate and encode the entire value:
TERMINAL
$ cue export nested-json.cue
{
"nestedJSON": "{\"innerString\":\"inside\"}",
"outerString": "outside"
}Encoding YAML to JSON
Use a different encoding package for encoding the nested value, such as yaml:
nested-yaml.cue
import "encoding/yaml"
_innerData: {
innerString: "inside"
}
nestedYAML: yaml.Marshal(_innerData)
outerString: "outside"TERMINAL
$ cue export nested-yaml.cue
{
"nestedYAML": "innerString: inside\n",
"outerString": "outside"
}
Choosing different encodings with cue export --out
Use a different encoding for the entire value via the --out flag, such as
yaml:
TERMINAL
$ cue export nested-json.cue --out yaml
nestedJSON: '{"innerString":"inside"}'
outerString: outside… or cue:
TERMINAL
$ cue export nested-yaml.cue --out cue
nestedYAML: """
innerString: inside
"""
outerString: "outside"For all encodings see the
encoding package listing.