0

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?

user3877654
  • 1,045
  • 1
  • 16
  • 40
  • Your desired output isn't JSON. Are you certain that's what you're trying to produce? – larsks Aug 11 '21 at 19:13
  • @larsks Correct, my desired output is YAML. I am using the -y option. Added to the question above – user3877654 Aug 11 '21 at 19:16
  • Note that your desired output isn't valid YAML, either. You would need to drop the `[` and `]`. That said, it's a weird combination of formatting -- using one syntax for the outer dictionary, but another for the inner dictionary. I wonder if any tool could produce exactly that? I'm not sure. – larsks Aug 11 '21 at 19:24
  • @larsks Apologies, you are right about the square brackets - I have been through so many iterations I am getting crosseyed. So I take from your response that this is not a normal use of jsonnet. Is there a way to customize the output or write more complex transformations? – user3877654 Aug 11 '21 at 19:29
  • I take back what I said earlier -- even with the fix I suggested, that's still not valid YAML. I've left an answer with one suggestion for getting a more canonical YAML format, but if you're looking for a jsonnet-only solution we'll need to wait for someone else. – larsks Aug 11 '21 at 19:40

1 Answers1

0

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).

larsks
  • 277,717
  • 41
  • 399
  • 399