skip to Main Content

Here is a sample input JSON with an array and an item to find:

Input :

{
  "numbers": [
    "1234",
    "9999",
    "0123",
    "2311",
    "9911",
    "5410"
  ],
  "number": "9999"
}

Output :

{
  "numberExists": "true"
}

Both the fields are dynamic and I cannot hard-code anything.

2

Answers


  1. The solution is based on similar post answered by @barbaros Özhan: Jolt Transform – Filter Array Where Fields equal

    [
      {
        "operation": "shift",
        "spec": {
          "number": {
            "$": "@(1)"
          },
          "numbers": {
            "*": {
              "*": {
                "$": "&1"
              }
            }
          }
        }
      }
    ,
      {
        "operation": "shift",
        "spec": {
          "*": {
            "*": {
              "number": {
                "#true": "numberExists"
              }
            }
          }
        }
       }
       ,
      {
        "operation": "default",
        "spec": {
          "numberExists": "false"
        }
      }
    
    
    ]
    
    Login or Signup to reply.
  2. You might use the following transformation as an alternative to my previous solution which is presented within the other answer :

    [
      { // match the attribute of the object and components of the array
        "operation": "shift",
        "spec": {
          "numbe*": {
            "$": "@0",    // pick up from the attribute of the object
            "*": {
              "$": "@0[]" // pick up from the components of the array
            }
          }
        }
      },
      { // determine whether exists a match
        "operation": "modify-overwrite-beta",
        "spec": {
          "*": "=size"
        }
      },
      { // check out for the size value of 2 to show up the existence
        "operation": "shift",
        "spec": {
          "*": {
            "2": {
              "#true": "numberExists"
            }
          }
        }
      }
    ]
    

    Another smart, even shorter solution might be

    [
      {
        "operation": "shift",
        "spec": {
          "numbe*": {
            "$": "@0",
            "*": {
              "#true": "@0"
            }
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "*": {
            "0": {
              "@": "numberExists"
            }
          }
        }
      }
    ]
    

    Btw, if returning the else case matters(unlike the the current question’s text), then you might add

      ,
      {
        "operation": "default",
        "spec": {
          "numberExists": "false"
        }
      }
    

    to the end of these transformations as presented in the other answer as well.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search