0

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
Psijic
  • 743
  • 7
  • 20

1 Answers1

1

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": {}
      }
    }
  ]
}
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • Thanks, works perfectly with the sample files. I try to understand how it should be configured with more complex files. – Psijic Feb 27 '19 at 10:49
  • Added other fields like in id: .[0].id but I think, should add a wildcard like * – Psijic Feb 27 '19 at 12:46