0

I cannot find the way to declare an array in an array with jsonnet. Here is the syntax I would like to render:

git/push/myrules:
  rules:
      - changes:
        - package.json
        - yarn.lock

I do succeed to setup changes as the first element of rules array

local git_push_instance() =
  {
    ['rules']: [
        'changes'
    ]
  };

{
  ['git/push/myrules']: git_push_instance()
}

Here is the output of command line jsonnet rules.jsonnet

{
   "git/push/myrules": {
      "rules": [
         "changes"
      ]
   }
}

But how to setup changes as an array with 2 entries : package.json and yarn.lock ?

I try this but got an error:

local git_push_instance() =
  {
    ['rules']: [
        changes: ['package.json', 'yarn.lock']
    ]
  };

{
  ['git/push/myrules']: git_push_instance()
}

STATIC ERROR: rules.jsonnet:4:16: expected a comma before next array element.

Richard
  • 23
  • 3

1 Answers1

2

The issue is that below construct has a key (changes:) while supposedly being an array entry:

    ['rules']: [
        changes: ['package.json', 'yarn.lock'] // incorrect
    ]

You need to change the above to emit an array of (mini)objects instead:

    ['rules']: [
        { changes: ['package.json', 'yarn.lock'] },
    ]

Just for completeness, pasting below the src and its output:

rules.jsonnet

local git_push_instance() =
  {
    rules: [
      { changes: ['package.json', 'yarn.lock'] },
    ],
  };

{
  'git/push/myrules': git_push_instance(),
}

output

NB: piping it thru yq -PI2 for a cleaner YAML output:

$ jsonnet rules.jsonnet | yq -PI2
git/push/myrules:
  rules:
    - changes:
        - package.json
        - yarn.lock
jjo
  • 2,595
  • 1
  • 8
  • 16
  • 1
    Thanks you so much @jjo I would had never imagined this kind of solution since {} was a dict in my mind ... actually it is an object as stated in jsonnet survival kit : https://learnxinyminutes.com/docs/jsonnet/ – Richard Sep 22 '22 at 09:25
  • You're welcome!, mind that a jsonnet object is pretty similar/same to a dict in other languages (like python), and the issue stands: there you need to provide an array of elements (indexed by their e.g. `[0]`, `[1]` ... indexes), each element in turn is an object (~dict). PS: appreciate if you can mark it as answered/resolved, to also help others with this result. Thanks! – jjo Sep 22 '22 at 12:22