6

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

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

我想为my_value[0]. 如何在 jsonnet 中引用它?

4

3 回答 3

10

您可以结合superjsonnet 的 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"
      }
   ]
}
于 2020-05-22T10:46:12.697 回答
7

一种使用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"
   }
]
于 2018-07-10T00:14:45.033 回答
1

IMO 更好的方法:将 转换arrayobject更容易重载,然后使用 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"
   }
]
于 2018-11-12T14:22:38.973 回答