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?
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"
}
]
}
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"
}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With