2

My biggest obstacle is that I don't know what the input payload looks like. But I need to convert any numerical Strings to numbers and "true" / "false" to true / false.

Do I need to recursively traverse the entire object / arrays of objects and inspect and assign each field or is there some kind of shortcut for this?

Of course, if I knew the structure of the input payload this wouldn't be a big deal. Unfortunately those are my requirements.

Dale
  • 1,289
  • 3
  • 16
  • 36

1 Answers1

4

@machaval is correct you got to traverse.

There is a way and depending on your background it maybe simple. This should be a good start even if its a bit inflexible:

%dw 2.0
output application/dw

var ds = [
    {
        a: "1",
        b: "2",
        c: "str",
        d: ["1","2","str","false"],
        e: "true"
    },
    {
        a: "1",
        b: "2",
        c: "str",
        d: ["1","2","str","false"],
        e: "true"
    }
]

import try,orElseTry,orElse from dw::Runtime
// Overloaded functions that traverse the types that I know
// my data structure contains.  I only traverse arrays and objects
// and the combination thereof. If you expect more types in your
// data you will have to add one overloaded function per datatype
// you expect to have up and beyond what I show below.
fun traverse(a: Array) = a map traverse($)
fun traverse(o: Object) = o mapObject {($$): traverse($)}
fun traverse(s: String) = 
        try(() -> s as Number) 
        orElseTry(() -> s as Boolean)
        orElse(s)   

---
traverse(ds)

edit: to include booleans

George
  • 2,758
  • 12
  • 16