jslt access parent field in for expression

Viewed 160

Hi, I want to use jslt to transform json , but happen an unsolvable problem.

    1. The input json data like this
{
    "user_id": "001",
    "friends": [{
        "friend_id": "002"
    }, {
        "friend_id": "003"
    }, {
        "friend_id": "004"
    }]
}
    1. Then , what output json data I expected like the follow :
[{
    "user_id": "001",
    "friend_id": "002"
}, {
    "user_id": "001",
    "friend_id": "003"
}, {
    "user_id": "001",
    "friend_id": "004"
}]
    1. In jslt expression , I use expression of for to traverse the array field friends :
[
    for (.friends) {
        "user_id": .user_id,
        "friend_id": .friend_id
    }
]
    1. However , the treansform result can't get field user_id
[{
    "friend_id": "002"
}, {
    "friend_id": "003"
}, {
    "friend_id": "004"
}]

How can I access field user_id out of the scope related array field friends ? Looking forward for your help, thanks !

2 Answers

The other answer is correct, but more complex than it needs to be. This is enough:

let user_id = (.user_id)
[ for (.friends) { "user_id": $user_id , "friend_id" : .friend_id } ]

Note that if you really want to report errors you could do it like this:

if (.user_id and .friends)
  let user_id = (.user_id)
  [ for (.friends) { "user_id": $user_id , "friend_id" : .friend_id } ]
else if (not(.user_id))
  error("user_id field missing")
else
  error("friends field missing")

Using error turns this into an exception at the Java level.

The reason the parent operator is not supported is that Jackson doesn't have a parent pointer in its nodes. That's a performance feature, because it means the node can be reused several places, saving CPU and memory.

You'll need to use a variable for the user_id, which you can then reference in the loop.

The following should fit your requirement:

if (.user_id)
  let user = .user_id
  if (.friends)
    [
      for (.friends) {
        "user_id": $user,
        "friend_id": .friend_id
      }
    ]
  else
    error("missing key 'friends'")
else
  error("missing key 'user_id'")
Related