fusion
fusion

Reputation: 1287

How to merge two json files with jq

I have a directory full of json files with the following structure e.g.: file1

{
    "products": [
        {"f1": "v1"},
        {"f1": "v2"}
    ]
}

file2:

{
    "products": [
        {"f1": "v3"},
        {"f1": "v4"}
    ]
}

The contents of ".products" are not the same as in the example but we can assume that they are well-formed more complicated json values.

I would like to produce a file with the following structure:

[
    {"f1": "v1"},
    {"f1": "v2"},
    {"f1": "v3"},
    {"f1": "v4"}
]

Any ideas on how to do this using jq?

Upvotes: 3

Views: 2929

Answers (1)

Aaron
Aaron

Reputation: 24802

You can use the following :

jq --slurp 'map(.products[])' /path/to/dir/*.json

where /path/to/dir/*.json should be either a list of files or a bash glob that will expand into the list of the JSON files you want to use. For instance for two files file1 and file2 in the current directory you can use file{1,2}, or simply file1 file2 which is what the previous glob will be expanded into.

The --slurp flag tells jq to read all its inputs in an array rather than working on them separately. We then map each object of this array (the original contents of the files) into the sequence of their products.

Upvotes: 6

Related Questions