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!

4
  • What is the exact data type of printers? org.json.JSONArray? javax.json.JsonArray? Something else? Commented Jan 25, 2018 at 0:20
  • printers will be org.json.JSONArray Commented Jan 25, 2018 at 1:10
  • Have you seen this? stackoverflow.com/questions/4784874/… Commented Jan 25, 2018 at 8:54
  • I would like to iterate it through JSONata as I am using the jsonata.js for querying the json scripts Commented Jan 25, 2018 at 9:01

1 Answer 1

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

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

3 Comments

The expression printers.($contains("HP") ? "HP-Printer" : $) will do the same. Note that the dot . operator is an implicit map function.
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?
Ah right, $number() doesn't tolerate the leading zeros. Raise an issue on GitHub - this could almost certainly be fixed.

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.