IBM / JSONata4Java

Open Source Java version of JSONata
Apache License 2.0
91 stars 38 forks source link

Append function result different than on try.jsonata.org #284

Closed Reid-McNaughton closed 10 months ago

Reid-McNaughton commented 11 months ago

Hello,

When I try the same as https://try.jsonata.org/Gt9VYEdVj in the TesterUI, I am getting the result:

{ "data" : [ { "name" : "obj 1", "id" : "obj1", "parentId" : "" }, { "name" : "obj 2", "id" : "obj2", "parentId" : "obj1" } ] }

Could you please advise if there is something wrong with my syntax, or if it is perhaps a bug? If there's another way to produce the same result, that would also be alright.

EDIT: after further testing, to me it looks like the issue is the append function is using a different context than in JS JSONata. To get the same result I need to use:

$.{ "data": data.{ "name": name, "id": id, "parentId": parentId, "children": children } ~> $append(**.children.{ "name": name, "id": id, "parentId": %.id }) } ~> $map(function($v) { {"data": $v.data.{"name": name, "id": id, "parentId": parentId}} })

Thank you.

wnm3 commented 10 months ago

Thank you Reid. I'm thinking you may have uncovered a bug, but I'm not sure if it is here or in Jsonata.org's implementation. What is happening is, the environment stack, upon exiting the first part of the equation before calling the chain has only the data's object and fields, so it has lost visibility of the children and only sees obj1 and obj2.

However, if you reset the environment to the top using $$ once you've entered the chained function you get the desired result:

$.{ "data": data.{ "name": name, "id": id, "parentId": parentId } ~> $append($$.**.children.{ "name": name, "id": id, "parentId": %.id }) }

Note the $append($$.**.children in above where your original call has no $$).

I created a different test to show the context that gets pushed into the chained append call here: https://try.jsonata.org/r0ZeiTLph and you can see what gets passed has no children: image

I'll pose your question in the jsonata slack channel to ensure I'm doing the proper environment setting.

If you agree, please close this issue.

wnm3 commented 10 months ago

Question in slack is here: https://jsonata.slack.com/archives/C2L3MR5EH/p1699631073708879

Reid-McNaughton commented 10 months ago

Thank you!