1

I would like to know how to iterate an array of primitives such as array of int or if it is as a simple array of string.

{
   "printers":[
      "HP-1234",
      "HP-Inkjet"
   ]
}

I would like to iterate the array and do some thing like this:

for( String obj:printers) {
    if(obj.contains("HP")) {
        //do something here
    }
}

How can i do this using JSONata?

Any help will be appreciated!

user1477232
  • 457
  • 1
  • 8
  • 17

1 Answers1

2

I figured out the solution which is as follows:

$map(printers, function($v, $i, $a) {
    $v~>$string()~>$contains("HP")?"HP Priter":$v
})

But since Am invoking the jasonata.js through Nashorn using java, I am not able to get the proper result.

This is what i have done:

        Object resultjson = inv.invokeMethod(expr, "evaluate", inputjson);        
        engine.put("resultjson", resultjson);
        Object result = engine.eval("JSON.stringify(resultjson);");
        System.out.println("Result:" + result);

The output am getting is Result: [object Object] Looking out for pointers to get the result in json format.

Note: I am using jsonata-es5.js as it is compatible with Nashorn

user1477232
  • 457
  • 1
  • 8
  • 17
  • The expression `printers.($contains("HP") ? "HP-Printer" : $)` will do the same. Note that the dot `.` operator is an implicit map function. – Andrew Coleman Jan 25 '18 at 13:49
  • Thanks a lot Andrew ! This helps. I have a question. Not on this expression but on another expression. Is it possible to convert a string which has a number to number using JSONata? For this JSON "printerId":"0000" when i try printerId~>$number() i get cannot convert a value to number. I understand this is because am trying to convert a string to number, but if i want to do is it possible? – user1477232 Jan 26 '18 at 02:35
  • Ah right, `$number()` doesn't tolerate the leading zeros. Raise an issue on GitHub - this could almost certainly be fixed. – Andrew Coleman Jan 26 '18 at 11:42