Search code examples
jsonequalityjolt

How to compare two string values in jolt


I want to filter out the input JSON based on two field values of input JSON.

Input JSON

[
  {
    "from_Store": "Test1",
    "to_Store": "Test1",
    "items": [
      {
        "UPC": "8240959370255",
        "shippedQuantity": 1
      }
    ]
  },
  {
    "from_Store": "Test2",
    "to_Store": "Test3",
    "items": [
      {
        "UPC": "8240959370210",
        "shippedQuantity": 1
      }
    ]
  }
]
  1. If the values of the from_Store and to_Store do not match, then keep that complete element of the map in the output JSON.
  2. If the values match, then the entire element should not be in the output

Expected output JSON

[
  {
    "from_Store": "Test2",
    "to_Store": "Test3",
    "items": [
      {
        "UPC": "8240959370210",
        "shippedQuantity": 1
      }
    ]
  }
]

Is there any function to compare the strings in Jolt?

Any help would be appreciated!


Solution

  • You can exchange key-value pairs for to_Store and from_Store attributes whether an array is formed or not per each node. If array is formed, then we'll get only 1 element, eg. values of the attributes are equal. Otherwise, we'll get 2 elements, so, we'll keep them as result such as

    [
      {
        "operation": "shift",
        "spec": {
          "*": {
            "*_*": "Cnt[&1].Count.@0" // to represent both of the attributes with unique underscores, eg. "from_store" and "to_store"
          },
          "@": "Original" // replicate the initial JSON value
        }
      },
      {
        "operation": "modify-overwrite-beta",
        "spec": {
          "Cnt": {
            "*": {
              "Count": "=size(@(1,&))"
            }
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "*": {
            "*": {
              "Count": "&1",
              "*": "&1.&"
            }
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "*": {
            "1": { // the second component
              "2": { // keep the value if its value is 2
                "@(2,[0])": "[]"
              }
            }
          }
        }
      }
    ]
    

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

    enter image description here