jsonjslt

jslt access parent field in for expression


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

{
  "user_id": "001",
  "friends": [
    {
      "friend_id": "002"
    },
    {
      "friend_id": "003"
    },
    {
      "friend_id": "004"
    }
  ]
}
[
  {
    "user_id": "001",
    "friend_id": "002"
  },
  {
    "user_id": "001",
    "friend_id": "003"
  },
  {
    "user_id": "001",
    "friend_id": "004"
  }
]
[
  for (.friends) {
        "user_id": .user_id,
        "friend_id": .friend_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 !


Solution

  • 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.