Psijic
Psijic

Reputation: 992

Merge array by using inner property

I have different language files like these:

file1

{
    "Pack": [
        {
            "id": "item1",
            "lang": {
                "en": {
                }
            }
        },
        {
            "id": "item2",
            "lang": {
                "en": {
                }
            }
        }
    ]
}

file2

{
    "Pack": [
        {
            "id": "item1",
            "lang": {
                "sp": {
                }
            }
        }
    ]
}

and I need to merge the same ids by lang field. Final file should looks like:

{
    "Pack": [
        {
            "id": "item1",
            "lang": {
                "en": {
                },
                "sp": {
                }
            }
        },
        {
            "id": "item2",
            "lang": {
                "en": {
                }
            }
        }
    ]
}

I think I should use something like more complex command but my starting point is:

jq -s '{ attributes: map(.attributes[0]) }' file*.json

Upvotes: 0

Views: 65

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134811

First you'll want to read in all files as input, then combine all Pack items and aggregating them into groups by id, then take those groups and arrange them to the result you need.

$ jq -n '
{Pack: ([inputs.Pack[]] | group_by(.id) | map({id: .[0].id, lang: (map(.lang) | add)}))}
' file*.json

This results in:

{
  "Pack": [
    {
      "id": "item1",
      "lang": {
        "en": {},
        "sp": {}
      }
    },
    {
      "id": "item2",
      "lang": {
        "en": {}
      }
    }
  ]
}

Upvotes: 1

Related Questions