Pennf0lio Pennf0lio - 4 days ago 7
JSON Question

Trying to merge two JSON file and reset ID values replace it with new incrementing values

I've been playing around with jq (https://stedolan.github.io/jq/) but I can't seem to make it work the way I want it to.

I was able to merge the two JSON file using this command

jq -s '[.[][]]' file*.json > combined_file.json
Now, I can't figure out how to go about in incrementing the 'id' value since when I merge it there will be duplicating id values.

My json files looks something like this:

file_a.json

[ {
"id": 0,
"fruit_name": "Apple",
"fruit_category": "category 1",
"fruit_count": 1
},
{
"id": 1,
"fruit_name": "Apricot",
"fruit_category": "category 2",
"fruit_count": 1
},
{
"id": 2,
"fruit_name": "Avocado",
"fruit_category": "category 3",
"fruit_count": 2
}
]


file_b.json

[ {
"id": 0,
"fruit_name": "Banana",
"fruit_category": "category 4",
"fruit_count": 1
},
{
"id": 1,
"fruit_name": "Bilberry",
"fruit_category": "category 5",
"fruit_count": 1
},
{
"id": 2,
"fruit_name": "Blackberry",
"fruit_category": "category 6",
"fruit_count": 2
}
]


I've been exploring this answer (How do I create an incremental index with jq) but I was not able to figure out how to make it work.

Answer

So if your goal is to reseed the ids, you could do this:

$ jq -n '[ foreach inputs[] as $i (0; .+1; $i*{id:(.-1)}) ]' file_?.json

I find using inputs instead of slurping easier to work with multiple inputs.

The idea is to take each of the items from input and update the id (by merging with an object with the desired id).

Comments