BMW
BMW

Reputation: 45223

How to make it work with filter in jq

I'd like to filter output from below json file to get all start with "tag_Name"

{
  ...

  "tag_Name_abc": [
    "10_1_4_3",
    "10_1_6_2",
    "10_1_5_3",
    "10_1_5_5"
  ],
  "tag_Name_efg": [
    "10_1_4_5"
  ],

  ...

}

Try something but failed.

$ cat output.json |jq 'map(select(startswith("tag_Name")))'
jq: error (at <stdin>:1466): startswith() requires string inputs

Upvotes: 4

Views: 6929

Answers (2)

jq170727
jq170727

Reputation: 14635

Here are a few more solutions:

1) combining values for matching keys with add

   . as $d
 | keys
 | map( select(startswith("tag_Name")) | {(.): $d[.]} )
 | add

2) filtering out non-matching keys with delpaths

 delpaths([
      keys[]
    | select(startswith("tag_Name") | not)
    | [.]
 ])

3) filtering out non-matching keys with reduce and del

 reduce keys[] as $k (
   .
 ; if ($k|startswith("tag_Name")) then . else del(.[$k]) end
 )

Upvotes: 2

Jeff Mercado
Jeff Mercado

Reputation: 134811

There's plenty of ways you can do this but the simplest way you can do so is to convert that object to entries so you can get access to the keys, then filter the entries by the names you want then back again.

with_entries(select(.key | startswith("tag_Name")))

Upvotes: 5

Related Questions