Search code examples
yamljsonnet

How to embed a literal json within a YAML using jsonnet?


Here's what I'm trying to achieve using jsonnet:

version: "v1"
data:
  j.json: |-
    {
      "foo": "bar"
    }

Here's my failed attempt:

local j = {
  foo: "bar"
};

local wrapper = {
  version: "v1",
  data: {
    'j.json': |||
      j
    |||
  }
};

std.manifestYamlDoc(wrapper)

In my attempt I'm getting the following result:

"data":
  "j.json": |
    j
"version": "v1"

How can achieve a desired result?


Solution

  • Couple things there:

    • the multiline string you build with the ||| expression is a literal, would need %<blah> format operator as any other string
    • looks like you want std.manifestJson() there
    • I'd rather take advantage of JSON being YAML and use jsonnet output, fwiw more legible:

    foo.jsonnet:

    local j = {
      foo: "bar"
    };
    
    local wrapper = {
      version: "v1",
      data: {
        'j.json': std.manifestJson(j)
      }
    };
    
    wrapper
    
    

    jsonnet output:

    $ jsonnet foo.jsonnet
    {
       "data": {
          "j.json": "{\n    \"foo\": \"bar\"\n}"
       },
       "version": "v1"
    }
    
    

    verifying j.json field with jq

    $ jsonnet foo.jsonnet | jq -r '.data["j.json"]' | jq
    {
      "foo": "bar"
    }