cancel
Showing results for 
Search instead for 
Did you mean: 

Flattening JSON

tsansoterra
New Contributor

Hello, I am struggling to flatten out some JSON. I looked at a bunch of the examples and did my best to figure it out but still having no luck.

Below is what I am looking for.

Current:

[
  {
    "items": {
      "item1": {
        "1": "i1_1",
        "2": "i1_2"
      },
      "item2": {
        "1": "i2_1",
        "4": "i2_2",
        "6": "i2_3"
      },
      "item3": {
        "5": "i3_1"
      }
    }
  }
]

Desired Output:

[
  {
    "items": {
      "item1_1": "i1_1",
      "item1_2": "i1_2",
      "item2_1": "i2_1",
      "item2_4": "i2_2",
      "item2_6": "i2_3",
      "item3_5": "i3_1"
    }
  }
]

Any help would be appreciated.

Thanks,

Todd

2 REPLIES 2

tsansoterra
New Contributor

Decided to go the JavaScript route. It’s not pretty but it seems to works.

JavaScript:

const json = '[{"items": {"item1": {"1": "i1_1","2": "i1_2"}, "item2": {"1": "i2_1","4": "i2_2","6": "i2_3"}, "item3": {"5": "i3_1"}}}]';

var myArr1 = JSON.parse(json);

var items = [];
var i = 0;

for(a in myArr1) {
    var myArr2 = myArr1[a];

    for(b in myArr2) {
        var myArr3 = myArr2[b];

        var key1;

        for (key1 in myArr3) {
            var myArr4 = myArr3[key1];
            
            var key2;

            for(key2 in myArr4) {
                var k = key1 + "_" + key2;
                var v = myArr4[key2];

                var item = "\"" + k + "\":\"" + v + "\"";

                items[i] = item;

                i++;
            }
        }
    }
}

console.log(JSON.parse("[{ \"items\":{" + items.toString().replace("'", "") + "}}]"));

Output:

[ { items:
     { item1_1: 'i1_1',
       item1_2: 'i1_2',
       item2_1: 'i2_1',
       item2_4: 'i2_2',
       item2_6: 'i2_3',
       item3_5: 'i3_1' } } ]

Would still be interested in a native SnapLogic Mapper solution if anyone has any ideas.

Hi @tsansoterra,

Try this expression:

$items.mapValues((v,k,o) => v.mapKeys((v1,k1,o1) => k+“_”+k1)).values().reduce((acc, v2) => acc.extend(v2))

Result window:
image

Cheers 🙂