Home > front end >  Using JOLT convert List to Array of Objects
Using JOLT convert List to Array of Objects

Time:11-16

I've spent quite a lot of time figuring it out but I'm stuck, I have a nested JSON and I want to enrich the values of "attr" with those matching the keys of "codes", thanks in advance.

My Input JSON:

{
  "items": {
    "a1b2xxxx": {
      "name": "item 1",
      "attr": [
        "A",
        "B",
        "C"
      ]
    },
    "c2b2cxxxx": {
      "name": "item 2",
      "attr": [
        "D",
        "E",
        "F"
      ]
    }
  },
  "codes": {
    "A": {
      "color": "green"
    },
    "B": {
      "size": "M"
    },
    "C": {
      "sku": "NS"
    },
    "D": {
      "stock": 2
    },
    "E": {
      "some_key": "some_value"
    },
    "F": {
      "foo": "bar"
    }
  }
}

My Desired Output JSON:

{
  "items": {
    "a1b2xxxx": {
      "name": "item 1",
      "attr": {
        "A": {
          "color": "green"
        },
        "B": {
          "size": "M"
        },
        "C": {
          "sku": "NS"
        }
      }
    },
    "c2b2xxxx": {
      "name": "item 2",
      "attr": {
        "D": {
          "stock": 2
        },
        "E": {
          "some_key": "some_value"
        },
        "F": {
          "foo": "bar"
        }
      }
    }
  },
  "codes": {
    "A": {
      "color": "green"
    },
    "B": {
      "size": "M"
    },
    "C": {
      "sku": "NS"
    },
    "D": {
      "stock": 2
    },
    "E": {
      "some_key": "some_value"
    },
    "F": {
      "foo": "bar"
    }
  }
}

My approach is following:

  1. Using cardinality operation convert attr to an array of objects
  2. Then maybe I can map values from codes using modify-default-beta

But I am stuck at step 1. Here is my transformer:

[
  {
    "operation": "cardinality",
    "spec": {
      "items": {
        "*": {
          "attr": "ONE"
        }
      }
    }
  }
]

CodePudding user response:

You can use a single shift transformation such as

[
  {
    "operation": "shift",
    "spec": {
      "items": {
        "*": {
          "name": "&2.&1.&",
          "attr": {
            "*": { // the level of the indexes of "attr" array, eg. 0,1,2
              "*": { // the level of the components of "attr" array, eg. A,B,C,D,E,F
                "@(5,codes.&)": "&5.&4.&" // going four levels up the tree to get the object labels of "a1b2xxxx" and "c2b2cxxxx"
              }
            }
          }
        }
      },
      "*": "&" // objects(attributes or array) other than "items", eg. "codes" 
    }
  }
]

the demo on the site enter image description here

  • Related