Jsonnet: How to iterate a jsonnet dict ?

Created on 9 Dec 2016  路  6Comments  路  Source: google/jsonnet

How can I iterate on the key/value of a hash/dict ?
The context is the generation of a configmap in kubernetes that can have any number of key/value.
This what I'm doing in jinja2 :

data:
  {% for key, value in config.iteritems() -%}
    {{key}}: "{{value}}"
  {% endfor -%}

The work around I found with jsonnet is instead of using a dict, is to use an array of {name: "key", value: "value"} and iterate on it:

data: {
  [elt.name]: elt.value for elt in variables.config
}

Is there a way to iterate on a dict in jsonnet like with jinja2?
if not, is it possible to return the keys set, so It would be possible to do:

data: {
  [key]: variables.config[key] for key in std.getDictKeys(variables.config)
}

Most helpful comment

Just for the note:

you can do:

local conf = {
  ports: [
    {p: 3000, type: 'http'},
    {p: 4000, osef: 1, type: 'grpc'},
  ],
};

{
  ports: [
    { p: p.p, type: p.type } for p in conf.ports
  ]
}

All 6 comments

There is std.objectFields(foo) and std.objectFieldsAll(foo) which includes the hidden ones. They return a sorted array of strings (i.e. one compatible with the set union / intersection functions).

Thanks

Just for the note:

you can do:

local conf = {
  ports: [
    {p: 3000, type: 'http'},
    {p: 4000, osef: 1, type: 'grpc'},
  ],
};

{
  ports: [
    { p: p.p, type: p.type } for p in conf.ports
  ]
}

@albttx can you help with this plz? I'm little puzzled

{
  _config+:: {
...
    alertproxy+:: {
      affinities+: [
        { key: 'key1', value: 'value1' },
        { key: 'key2', value: 'value2' },
      ],
      containers: [],
    },
  },

...
    local expression = [
        matchExpression.new() +
        matchExpression.withOperator('In') +
        matchExpression.withKey($._config.alertproxy.affinities.key) +
        matchExpression.withValues($._config.alertproxy.affinities.value),
    ];
...
}

@Asgoret sorry i didn't used jsonnet since my post... :/ can't help you

good luck 馃憤

@Asgoret Can you explain what is your problem / question?

Was this page helpful?
0 / 5 - 0 ratings