Search code examples
jsonjolt

Replace value in JSON with Jolt


I'd like to replace a value in a JSON with Jolt but I haven't managed to do so.

My JSON :

{
  "MIRecord": [
    {
      "RowIndex": "0",
      "NameValue": [
        {
          "Name": "MBWHLO",
          "Value": "123"
        },
        {
          "Name": "MBITNO",
          "Value": "123"
        },
        {
          "Name": "V_NETA",
          "Value": "123"
        }
      ]
    },
    {
      "RowIndex": "1",
      "NameValue": [
        {
          "Name": "MBWHLO",
          "Value": "123"
        },
        {
          "Name": "MBITNO",
          "Value": "123"
        },
        {
          "Name": "V_NETA",
          "Value": "123"
        }
      ]
    }
  ]
}

I want to replace :

  • MBWHLO to CHANGE1
  • MBITNO to CHANGE2
  • V_NETA to CHANGE3

My target JSON :

{
  "MIRecord": [
    {
      "RowIndex": "0",
      "NameValue": [
        {
          "Name": "CHANGE1",
          "Value": "123"
        },
        {
          "Name": "CHANGE2",
          "Value": "123"
        },
        {
          "Name": "CHANGE3",
          "Value": "123"
        }
      ]
    },
    {
      "RowIndex": "1",
      "NameValue": [
        {
          "Name": "CHANGE1",
          "Value": "123"
        },
        {
          "Name": "CHANGE2",
          "Value": "123"
        },
        {
          "Name": "CHANGE13",
          "Value": "123"
        }
      ]
    }
  ]
}

I try this but i change all of "Name" value to CHANGE1

[
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "MIRecord": {
        "*": {
          "NameValue": {
            "*": {
              "Name": "CHANGE1"
            }
          }
        }
      }
    }
  }
]

I don't know if I'm using the right function to replace or if I need to rebuild the whole json. But I'd like to avoid having to redo the json because the input JSON isn't static.

Does anyone have a solution please?


Solution

  • You can use # wildcards in order to define new fixed values while conditionally match each one within a shift transformation such as

    [
      {
        "operation": "shift",
        "spec": {
          "MIRecord": {
            "*": {
              "NameValue": {
                "*": {
                  "Name": {
                    "MBWHLO": { "#CHANGE1": "&6[&5].&4[&3].&2" },
                    "MBITNO": { "#CHANGE2": "&6[&5].&4[&3].&2" },
                    "V_NETA": { "#CHANGE3": "&6[&5].&4[&3].&2" }
                  },
                  "*": "&4[&3].&2[&1].&"
                }
              },
              "*": "&2[&1].&"
            }
          }
        }
      }
    ]
    

    the demo on the site http://jolt-demo.appspot.com/ is :

    enter image description here