Jq: How to merge 2 files json in one with 1 array only for all ? thx

Created on 7 Jun 2015  路  6Comments  路  Source: stedolan/jq

Hello,
I'm a french user of linux ubuntu, for my project about streaming i need to do specific opperations about scrapping and json on my vps ubuntu.

So i want use this great tool with my ubunu.
The problem :

I have a series of files in a folder like that:
a-01.json
a-02.json
a-03.json
etc...

All json generated by my module node js for scrapping look like that :

a-01.json :

[
{
"title1": "title1",
"title2": "title2",
},
{
"title1": "title1",
"title2": "title2",
}

]

a-02.json :
[
{
"title1": "title1",
"title2": "title2",
},
{
"title1": "title1",
"title2": "title2",
}

]

And i want to merge all files in one json and i want it look like that :

[
{
"title1": "title1",
"title2": "title2",
},
{
"title1": "title1",
"title2": "title2",
},
{
"title1": "title1",
"title2": "title2",
},
{
"title1": "title1",
"title2": "title2",
}
]

I use this command but not exactly wahat i want :

jq -s '.' a-*.json > manifest.json

Thank you verry much for your help the comunauty !

support

Most helpful comment

Using the -s option will return an array containing the contents of the input JSON files, which, in your case, are also arrays. This means that you need to spread (鈥]) two array levels, and collect ([鈥) the result.

jq -s '[.[][]]' a-*.json > manifest.json

All 6 comments

Using the -s option will return an array containing the contents of the input JSON files, which, in your case, are also arrays. This means that you need to spread (鈥]) two array levels, and collect ([鈥) the result.

jq -s '[.[][]]' a-*.json > manifest.json

Wooowww the fastest answer i have ever seen in my life of dev !
And it's work verry well on first test, Thank you Segnor slapresta.

You're welcome! If you need anything else, try the jq tag on StackOverflow; they're even faster over there!

Ok thanks, i have litle problem :the result in not in order cetain elements comes before others, the alphabetical is not respected. How can i do that ?

It would seem that you want to sort the array previously obtained. If, for example, you want to sort by the values of the keys "title1" and "title2", then the relevant filter would be:

sort_by([.title1, .title2])

By the way, as @slapresta pointed out, usage questions are probably best asked at http://stackoverflow.com/questions/tagged/jq

Ok thx i will reading somes documentation about that and will going to satckoverflow for next questions.

Was this page helpful?
0 / 5 - 0 ratings