Search code examples
jsonstringformatjsonnet

Jsonnet: How to do String Formatting + String Joining together?


I want to make this expression more readable so that it's easier to add new variables if needed, so I tried writing something like this:

std.format('{%s}',
        std.join(', ', [
        std.format('"account": "%s"', dev_account_id),
        std.format('"service": "%s"', business_service),
        std.format('"dir": "%s"', kms_module_dir)
        ])
      )

Unfortunately, I'm getting this error:

app_metaflow/shore/main.pipeline.jsonnet:(58:19)-(72:8)\tobject <anonymous>\n\tDuring manifestation\t\n"
RUNTIME ERROR: Missing argument: vals
    /mnt/data/jenkins/workspace/d-platform_fusmltrn-app_metaflow/shore/main.pipeline.jsonnet:63:9-35    thunk from <thunk from <thunk from <object <anonymous>>>>
    /mnt/data/jenkins/workspace/d-platform_fusmltrn-app_metaflow/shore/main.pipeline.jsonnet:(59:9)-(71:11) thunk from <object <anonymous>>
    <std>:769:20-24 thunk from <function <anonymous>>
    <std>:32:25-26  thunk from <function <anonymous>>
    <std>:32:16-27  function <anonymous>
    <std>:769:8-25  function <anonymous>

I basically want to create a string equivalent of this, but more readable

std.format('{"account": "%s", "service": "%s", "dir": "%s"}', [dev_account_id, business_service, kms_module_dir])

Solution

  • Interesting, as your example did work for me (using jsonnet v0.19.1), nevertheless it looks like your building a JSON string, thus it may be worth using native function(s) to do so.

    Below example shows your implementation, together with a JSON- native approach:

    src: foo.jsonnet

    local dev_account_id = 'someId';
    local business_service = 'someService';
    local kms_module_dir = 'someDir';
    [
      // Manual string formatting
      std.format(
        '{%s}',
        std.join(', ', [
          std.format('"account": "%s"', dev_account_id),
          std.format('"service": "%s"', business_service),
          std.format('"dir": "%s"', kms_module_dir),
        ])
      ),
      // Looks like JSON, let's use native function
      std.manifestJsonMinified({
        account: dev_account_id,
        service: business_service,
        dir: kms_module_dir,
      }),
    ]
    

    output

    $ jsonnet foo.jsonnet
    [
       "{\"account\": \"someId\", \"service\": \"someService\", \"dir\": \"someDir\"}",
       "{\"account\":\"someId\",\"dir\":\"someDir\",\"service\":\"someService\"}"
    ]