Search code examples
arraysjsondictionarykeyjsonata

Combine dictionaries with same key using JSONata


I am trying to combine the information from two dictionaries into one. I have a JSON like this:

{
 "First": {
          "example1": [
            {
              "key": "A",
              "value_1": 5
            },
            {
              "key": "B",
              "value_1": 1
            },
            {
              "key": "C",
              "value_1": 6
            },
            {
              "key": "D",
              "value_1": 8
            },
            {
              "key": "E",
              "value_1": 2
            }
         ]
 },
 "Second":{
          "example2": [
            {
              "key": "A",
              "value_2": 2
            },
            {
              "key": "B",
              "value_2": 1
            },
            {
              "key": "C",
              "value_2": 1
            }
         ]
 }
}

What I'm trying to get is one JSON with the same key and the two different values. Ideally if there are no values for value_2, then it should just be 0. Something like this:

{
 "Result":[
            {
              "key": "A",
              "value_1": 5,
              "value_2": 2

            },
            {
              "key": "B",
              "value_1": 1,
              "value_2": 1
            },
            {
              "key": "C",
              "value_1": 1,
              "value_2": 1
            },
            {
              "key": "D",
              "value_1": 8,
              "value_2": 0
            },
            {
              "key": "E",
              "value_1": 2,
              "value_2": 0
            }
         ]
 }

Solution

  • Try:

    (*.*{key: {
        'key': $distinct(key),
        'value_1': value_1, 
        'value_2': [value_2, 0][0]
        }})
    .{'Result': *}
    

    See https://try.jsonata.org/kObVLMPnj