zencraft
zencraft

Reputation: 111

Update values in one array based on another in the same JSON file

I have a JSON file like this:

{
    "download": [0, 0, 0, 0],
    "files": [ "file1.txt", "file1.iso", "file2.txt", "file2.iso" ] 
}

For each element in files[] ending in .txt I want to set the corresponding element in download[] to 1. How do I do that in JQ? I googled around but don't really understand JQ syntax.

Upvotes: 0

Views: 58

Answers (1)

oguz ismail
oguz ismail

Reputation: 50750

In this case constructing download from scratch would be much easier.

.download = (.files | map(if endswith(".txt") then 1 else 0 end))

Online demo

But the title asks how to update one array based on another?, and here is one way of doing it:

.download = reduce (.files | path(.[] | select(endswith(".txt")))) as $p (.download; setpath($p; 1))

Online demo

Upvotes: 2

Related Questions