I have a list of json files like:
file1.json
[
{obj1}
]
file2.json
[
{obj2}
]
and I want to merge them all into one file:
[
{obj1},
{obj2}
]
How can I achieve this using jq?
You can use the following :
jq -s 'add' file1.json file2.json
Using -slurp mode makes jq handle multiple inputs in a single pass, concatenating them into an array that contains your two arrays. We can merge them into a single one by transforming the input array with the add filter which yields the sum of each element as if using +; using it on arrays returns a single array with all the elements of both arrays.
It can be done by invoking jq two times like this:
jq -c '.[]' *.json | jq -s
*.json is evaluated by the shell and replaced with the list of matching files. jq gets the names of all JSON files in the current directory as arguments. It reads them one by one and runs the program .[] on the JSONs they contain.
Each JSON file contains an array. .[] extracts the items from the array and dumps them.
-c tells jq to output each value (the items extracted by .[]) on a single line.
The output of the first jq command is composed of one line for each object from the arrays stored in the input files.
This output is then fed to the second jq command whose -s argument tells it to read everything (it normally reads one JSON at a time) and put all the objects it decodes from the input JSONs into an array. This is exactly what you want.