Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dataweave "contains" returns false with "keysOf" output even though the key is contained

I’m facing towards a misbehavior of the function keysOf combined with the method contains.

Given an object like:

    {
     "keyA":1,
     "keyB":2
    }

And given the Dataweave script like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

keysOf(payload) contains "keyA"

I’m expecting to have true as outcome, but it returns false.

The keysOf function returns an array containing the keys of the previously mentioned object, like so:

[
 "keyA",
 "keyB"
]

Which, if used in the following script, it returns the true expected outcome:

[ "keyA", "keyB" ]  contains "keyA"

The workaround I tried to implement, storing the keysOf outcome into a variable, doesn’t work either:

%dw 2.0
output application/json
var keysOfPayload=keysOf(payload)
---
keysOfPayload contains "keyA"

The goal of this question, is not to find a workaround, for instance using the question mark selector against the key, works as expected:

%dw 2.0
output application/json
var object= {"keyA":1,"KeyB":2}
---
object.keyA?

Rather, I’m willing to understand why the combination of keysOf and contains is not effective as expected.

>Solution :

The keysOf() works exactly as expected. The problems is a common misconception of how it works. It returns an array of the keys with the Key type. When you try to compare it to a String the comparison returns false correctly.

To make this work you need to do one of two things:

  1. Recommended use the functions namesOf() instead: namesOf(a) contains "keyA". Note that namesOf() converts the keys to strings and returns an array of Strings.
  2. Convert the String to a Key explicitly before using: keysOf(a) contains ("keyA" as Key)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading