Search code examples
jsonnet

How do I correctly format this jsonnet array output?


I have the following JSON and am using the -y option to produce a yaml output.

{
  array: [
    {item1: 1},
    {item2: 2},    
  ]   
}

I would like to produce (desired)

{
   "array": 
      -  "item1": 1,
      -  "item2": 2
}

but I am getting

{
   "array": [
      {
         "item1": 1
      },
      {
         "item2": 2
      }
   ],
}

Note the curly brackets in the actual output. Is it possible to use jsonnet to produce the desired yaml output?


Solution

  • If you wanted to go from this (which is both valid JSON and valid YAML):

    {
       "array": [
          {
             "item1": 1
          },
          {
             "item2": 2
          }
       ],
    }
    

    To this:

    array:
      - item1: 1
      - item2: 2
    

    You could just pipe the result through yq:

    $ cat input.jsonnet
    {
      array: [
        {item1: 1},
        {item2: 2},    
      ]   
    }
    $ jsonnet input.jsonnet | yq -y
    array:
      - item1: 1
      - item2: 2
    

    If you really want the final output to look like this:

    {
      "array":
        - item1: 1
        - item2: 2
    }
    

    Note that is neither valid JSON nor valid YAML (try pasting that into a YAML validator, for example). You would need to write some sort of custom output format to get that output (perhaps the docs in the "Custom Output Formats" section would be helpful on this front, although I haven't tried any of that myself).