使用jsonnet更改json字符串

时间:2019-02-26 08:11:35

标签: json kubernetes prometheus jsonnet

我想使用jsonnet在下面的json中更改namespace中的alok-pod.json

{
    "apiVersion": "v1",
    "items": [
        {
            "apiVersion": "v1",
            "data": {
                "alok-pod.json": "{\n  \"namespace\": \"alok\",\n  \"editable\": true,\n}"
            }
        },
    ]
}

请建议如何使用jsonnet做到这一点?

1 个答案:

答案 0 :(得分:1)

请注意,您需要一个由master生成的jsonnet二进制文件,因为std.parseJson()截至2019-02-26尚未发布。

  

input.json

{
    "apiVersion": "v1",
    "items": [
        {
            "apiVersion": "v1",
            "data": {
                "alok-pod.json": "{\n  \"namespace\": \"alok\",\n  \"editable\": true\n}"
            }
        },
    ]
}
  

edit_ns.jsonnet

// edit_ns.jsonnet for https://stackoverflow.com/questions/54880959/make-changes-to-json-string-using-jsonnet
//
// NOTE: as of 2019-02-26 std.parseJson() is unreleased, 
// need to build jsonnet from master.

local input = import "input.json";

local edit_ns_json(json, ns) = (
  std.manifestJson(std.parseJson(json) { namespace: ns })
);

local edit_ns(x, ns) = (
  x {
    local d = super.data,
    data+: {
      [key]: edit_ns_json(d[key], ns) for key in std.objectFields(d)
    }
  }
);

[edit_ns(x, "foo") for x in input.items]
  

示例运行:

$ jsonnet-dev edit_ns.jsonnet
[
   {
      "apiVersion": "v1",
      "data": {
         "alok-pod.json": "{\n    \"editable\": true,\n    \"namespace\": \"foo\"\n}"
      }
   }
]