Search code examples
jsonnet

Update an existing array element with 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?


Solution

  • 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"
       }
    ]