Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update an existing array element with jsonnet

Tags:

jsonnet

I am using jsonnet to read in a value which consists of an array. I want to modify the first element in that array to add a value. The data structure looks like this:

{
   "my_value": [
      {
         "env": "something"
      },
      {
         "var": "bar"
      }
   ]
}

I want to add a value to my_value[0]. How can I reference that in jsonnet?

like image 312
jaxxstorm Avatar asked Jul 09 '18 23:07

jaxxstorm


2 Answers

You can combine super with jsonnet's python style array slicing:

{
   "my_value": [
      {
         "env": "something"
      },
      {
         "var": "bar"
      }
   ]
} 
+ 
{
  "my_value": [
    super.my_value[0] + {
      "env_2": "something_else"
    },
  ] + super.my_value[1:]
}

Results in:

{
   "my_value": [
      {
         "env": "something",
         "env_2": "something_else"
      },
      {
         "var": "bar"
      }
   ]
}
like image 179
muxmuse Avatar answered Sep 21 '22 21:09

muxmuse


A possible approach using https://jsonnet.org/ref/stdlib.html#mapWithIndex as per below:

$ cat foo.jsonnet 
local my_array = [
  {
    env: "something",
  },
  {
    var: "bar",
  },
];
local add_by_idx(idx) = (
  if idx == 0 then { extra: "stuff" } else {}
);
std.mapWithIndex(function(i, v) v + add_by_idx(i), my_array)

$ jsonnet foo.jsonnet 
[
   {
      "env": "something",
      "extra": "stuff"
   },
   {
      "var": "bar"
   }
]
like image 26
jjo Avatar answered Sep 22 '22 21:09

jjo