0

I want to check whether all the required keys are present in the input JSON and filter out those that are not present. I tried the script but I am getting the below error. How to fix this?

Input:

{"req":{
    "messageList": [
        {
            "res":1,
          
            "id":"test"
        }
    ]
}}

Required Keys:

var keys = ["res","req"]

DW Script:

%dw 2.0
output application/json
var keys = ["res"]
var p =payload.req.messageList[0]



fun getAllAbsentKeys(obj) = obj filterObject ((value, key, index) -> keys filter ((item, index) -> item == key) )
---
getAllAbsentKeys(p)

output:

["req"]


Cannot coerce Array ([]) to Boolean

1 Answer 1

3

If the intention is to get for an object what keys are missing:

%dw 2.0
output application/json
import * from dw::core::Arrays
var keys = ["res", "req"]
var p =  [
            {
                "res": 1
            },
            {
                "res": 2,
                "req": "test"
            },
            {
                "ret": 3,
                "id": "test"
            },
            {
                "age": 4,
                "req": 8,
                "id":"test"
            }
        ]   

fun missingKeys(obj, keys) = keys filter !(namesOf(obj) contains $) 
---
p map missingKeys($, keys)

Output:

[
  [
    "req"
  ],
  [
    
  ],
  [
    "res",
    "req"
  ],
  [
    "res"
  ]
]

Note that I didn't use your payload since it is not needed to explain the solution. Where the input is coming is up to you. It is better to minimize the problem and focus in its solution.

Sign up to request clarification or add additional context in comments.

1 Comment

Let me put it this way, var requiredKeys = ["key1", "key2"] which are required. In my input assume I am getting only key1 and not the other one. I need to get the list of keys that are not present in the input against the required one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.