Search code examples
jslt

Can you retrieve the value of a JSON object using the key of another in JSLT?


I am trying to compare the contents of two JSON objects and keep only the elements that are different using JSLT. My ultimate goal is to build a generic script that recursively evaluates the contents of the objects (the contents can change and contain multiple objects and arrays that may or may not be nested). I am trying to accomplish this by using one object to cycle through the elements with a for loop and comparing each element against the corresponding one in the other object. However, I cannot figure out how to retrieve the corresponding values. Here is a sample JSON:

{
  "itemOne": {
    "name": "Ralph"
  },
  "itemTwo": {
    "name": "Steve"
  }
}

I am trying to use the key value from itemTwo to retrieve the value from itemOne. So in this example, want to use the key "name" from itemTwo, to retrieve the value of "name" from itemOne, in this case, 'Ralph'.

I have tried the following:

let itemOne = .itemOne
{
  for(.itemTwo)
    .key : $itemOne.value
}

This returns null. Assuming that it is actually looking for the object 'value' in itemOne and not using the .value content node value.

let itemOne = .itemOne
{
  for(.itemTwo)
    .key : $itemOne
}

Returns the entire contents of itemOne and not the value of the name object.

let itemOne = .itemOne
{
  for(.itemTwo)
    let itemOneName = "$itemOne" + .key
    let fixed = ""
    .key : $itemOneName
}

Returns {"name" : "$itemOnename"}

let itemOne = .itemOne
{
  for(.itemTwo)
    .key : $itemOne(.value)
}

Returns the error- com.schibsted.spt.data.jslt.JsltException: Parse error: Encountered " "(" "( "" at line 5, column 20.

Is what I am trying to do even possible or is there another solution?


Solution

  • I think you were already very close to the solution. The desired behavior can be achieved with get_key.

    Does the same as .key on object, with the difference that here the key can be dynamic. That is, it can come from a variable, be looked up in input data, and so on.

    So please try the following:

    let itemOne = .itemOne
    {
      for(.itemTwo)
        .key : get-key($itemOne, .key)
    }