Search code examples
jsonjolt

JOLT: select/change child by attribute


I'm new to JOLT and googled a lot (maybe using wrong search terms) but could not find an answer to my seemingly simple problem. I want to change an attribute of a child which is identified by another attribute.

So I have this input:

{
  "Level0": {
    "Level-1": {
      "ID": 10,
      "Status": "OK",
    },
    "Level-2": {
      "ID": 20,
      "Status": "OK",
    },
    "Level-3": {
      "ID": 30,
      "Status": "OK",
    }
  }
}

and want to change the 'Status' value of the child with ID=20 so that this is the expected output:

{
  "Level0": {
    "Level-1": {
      "ID": 10,
      "Status": "OK",
    },
    "Level-2": {
      "ID": 20,
      "Status": "Running",
    },
    "Level-3": {
      "ID": 30,
      "Status": "OK",
    }
  }
}

I tried many variants with "modify-overwrite-beta" but could not get the desired result.

Can someone help please?


Solution

  • You can use a conditional within a shift transformation specification such as

    [
      {
        "operation": "shift",
        "spec": {
          "*": { // the outermost level 
            "*": {
              "ID": {
                "@": "&3.&2.&1", // replicate the ID's value
                "20": { "#Running": "&4.&3.Status" }, // express fixed value by prefixing it with #
                "*": { "@2,Status": "&4.&3.Status" } // if ID is not equal to 20, the keep the current value of the "Status"
              }
            }
          }
        }
      }
    ]
    

    where the identifiers with ampersands( &1,&2... ) represent the name of the nodes received by going that much level up the tree respectively.

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

    enter image description here