使用jsonnet更新现有的数组元素

时间:2018-07-09 23:41:38

标签: jsonnet

我正在使用jsonnet读取由数组组成的值。我想修改该数组中的第一个元素以添加一个值。数据结构如下:

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

我想为my_value[0]添加一个值。如何在jsonnet中引用它?

3 个答案:

答案 0 :(得分:3)

使用https://jsonnet.org/ref/stdlib.html#mapWithIndex的可能方法如下:

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

答案 1 :(得分:3)

您可以将super与jsonnet的python样式数组切片结合使用:

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

结果:

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

答案 2 :(得分:0)

一种IMO更好的方法:将array转换为object以便于重载,然后再利用jsonnet通过对其键进行alpha排序来处理对象这一事实:

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