Search code examples
jsonjolt

How to map a list of id's to list of objects


How to stitch list of id's for each object of a list? In the below request, I want to stitch the id to each fruit and return the object. For each fruit one id from id's should be stitched.

How to stitch list of id's for each object of a list? In the below request, I want to stitch the id to each fruit and return the object. For each fruit one id from id's should be stitched.

INPUT:

{
  "ids": [
    "1",
    "2",
    "3"
  ],
  "request": {
    "Fruits": {
      "item": [
        {
          "fruit": {
            "Type": "fruit",
            "name": "apple"
          }
        },
        {
          "fruit": {
            "Type": "fruit",
            "name": "banana"
          }
        },
        {
          "fruit": {
            "Type": "fruit",
            "name": "orange"
          }
        }
      ]
    }
  }
}

Expected Output

{
  "request": {
    "Fruits": {
      "item": [
        {
          "fruit": {
            "Type": "fruit",
            "name": "apple",
            "id": "1"
          }
        },
        {
          "fruit": {
            "Type": "fruit",
            "name": "banana",
            "id": "2"
          }
        },
        {
          "fruit": {
            "Type": "fruit",
            "name": "orange",
            "id": "3"
          }
        }
      ]
    }
  }
}

Solution

  • You should traverse levels upto the place where ids stays starting from the innermost part, so 5 levels needed, while using the indexes of the item array such as

    [
      {
        "operation": "shift",
        "spec": {
          "request": {
            "*": {
              "*": {
                "*": {
                  "*": {
                    "*": "&5.&4.&3[&2].&1.&",//replicates the current innermost atributes
                    "@5,ids[&1]": "&5.&4.&3[&2].&1.id"
                  }
                }
              }
            }
          }
        }
      }
    ]
    

    the demo on the site https://jolt-demo.appspot.com/ is

    enter image description here