2

I'm trying to map one key to each value in array to a new array by using JOLT. Could someone please help give me a solution for this:

My JSON:

[
  {
    "person_id": "1",
    "resources": ["asd", "zxc"]
  },
  {
    "person_id": "2",
    "resources": ["ghj", "asd"]
  }
]

And my expected JSON:

[
  {
    "person_id": "1",
    "resource": "asd"
  },
  {
    "person_id": "1",
    "resource": "zxc"
  },
  {
    "person_id": "2",
    "resource": "ghj"
  },
  {
    "person_id": "2",
    "resource": "asd"
  }
]

I had tried this Jolt Specification

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "resources": {
          "*": {
            "@(2,person_id)": "[&].person_id",
            "@": "[&].resource"
          }
        }
      }
    }
  }
]

But no luck it always maps all values at the same index to 1 array.

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55

2 Answers2

1

You can use two consecutive shift transformation specs by walking through the resources array within the first one such that

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*s": { // this tecnique stands for extracting by the replacement of the asterisk through use of &(2,1) below
          "*": {
            "@(2,person_id)": "[&3].&1.person_id", // to separate by indexes of the array to generate three level for three independent objects
            "@": "[&3].&1.&(2,1)"
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": ""
      }
    }
  }
]

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

enter image description here

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
  • 1
    Great! thank you a lot, exactly what I need. BTW, do you know any useful document to learn those syntax, I messed up with it several days – Đình Tuyên Nov 29 '22 at 14:53
  • You're welcome. There are some links those I like [1](https://erbalvindersingh.medium.com/applying-jolttransform-on-json-object-array-and-fetching-specific-fields-48946870b4fc), [2](https://intercom.help/godigibee/en/articles/3096940-simple-if-else-with-jolt), [3](https://github.com/bazaarvoice/jolt/releases), [4](https://cool-cheng.blogspot.com/2019/12/json-jolt-tutorial.html). Have a nice day @ĐìnhTuyên ! – Barbaros Özhan Nov 29 '22 at 14:57
1

You can use this jolt spec:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*s": {
          "*": {
            "@(2,person_id)": "@(1).person_id",
            "@": "@(1).&(2,1)"
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": ""
    }
  }
]
Mohammadreza Khedri
  • 2,523
  • 1
  • 11
  • 22