7

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?

jaxxstorm
  • 12,422
  • 5
  • 57
  • 67

3 Answers3

11

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"
      }
   ]
}
muxmuse
  • 385
  • 2
  • 9
8

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"
   }
]
jjo
  • 2,595
  • 1
  • 8
  • 16
1

A IMO better approach: converting the array to object for easier overloading, then ab-using the fact that jsonnet handles objects by alpha-sorting its keys:

$ cat foo.jsonnet
local array_a = [
  { env: "something" },
  { var: "bar" },
];

local array_b = [
  {},
  { extra: "stuff" },
];

// "Standarize" index key string as "%06d"
local _idx(i) = ("%06d" % [i]);

// Convert array [elem1, elem2, ...] to object as { 000000: elem0, 000001: elem1, ...}
local _to_obj(a) = std.foldl(
  function(x, y) x + y,
  std.mapWithIndex(function(i, v) { [_idx(i)]: v }, a),
  {}
);

local _to_array(obj) = [obj[k] for k in std.objectFields(obj)];

_to_array(std.mergePatch(_to_obj(array_a), _to_obj(array_b)))

$ jsonnet foo.jsonnet 
[
   {
      "env": "something"
   },
   {
      "extra": "stuff",
      "var": "bar"
   }
]
jjo
  • 2,595
  • 1
  • 8
  • 16