Make changes to json string using jsonnet

2/26/2019

I want to change namespace in alok-pod.json in the below json using jsonnet.

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

Please suggest how this can be done using jsonnet?

-- Alok Kumar Singh
json
jsonnet
kubernetes
prometheus

1 Answer

2/26/2019

NOTE you'll need a jsonnet binary built from master, as std.parseJson() is not yet released as of 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]

Example run:

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