'jq select a subset of paths selected
I am getting mutiple array of paths contains keywords 'headline' below:
jq -c 'paths | select(.[-1] == "headline")' nytimeseuro.json
["data","legacyCollection","collectionsPage","stream","edges",0,"node","headline"]
["data","legacyCollection","collectionsPage","stream","edges",1,"node","headline"]
["data","legacyCollection","collectionsPage","stream","edges",2,"node","headline"]
["data","legacyCollection","collectionsPage","stream","edges",3,"node","headline"]
["data","legacyCollection","collectionsPage","stream","edges",4,"node","headline"]
["data","legacyCollection","headline"]
Can I select them based on array index ? like Output[0:2] select just
["data","legacyCollection","collectionsPage","stream","edges",0,"node","headline"]
["data","legacyCollection","collectionsPage","stream","edges",1,"node","headline"]
["data","legacyCollection","collectionsPage","stream","edges",2,"node","headline"]
Or Output[-1] select just
["data","legacyCollection","headline"]
I tried command below , but that seems not to be what I want, it just sliced each path I got, rather than select subset of all paths returned:
jq -c 'paths | select(.[-1] == "headline")[:3]' nytimeseuro.json
["data","legacyCollection","collectionsPage"]
["data","legacyCollection","collectionsPage"]
["data","legacyCollection","collectionsPage"]
["data","legacyCollection","collectionsPage"]
["data","legacyCollection","collectionsPage"]
["data","legacyCollection","headline"]
Solution 1:[1]
paths produces a stream, whereas you evidently want an array from which you can easily extract the items of interest. For example:
[paths | select(.[-1] == "headline")][0:2]
Stream-oriented alternatives are also available, e.g. limit(2; paths ....)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
