Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq: filter input based on if key ends with specified string

Tags:

json

key

filter

jq

I get this JSON data mess in and I need to extract the list of types:

{
  "token/": {
    "accessor": "auth_token_909d6a81",
    "config": {
      "default_lease_ttl": 0,
      "max_lease_ttl": 0
    },
    "description": "token based credentials",
    "local": false,
    "seal_wrap": false,
    "type": "token"           <-- I need to extract this value ...
  },
  "userpass/": {
    "similar_to": {
      "above": null
    },
    "description": "",
    "local": false,
    "seal_wrap": false,
    "type": "userpass"        <-- ... and this one
  },
  "request_id": "f2a4c135-f699-f29d-ca7c-3320dce0a550",
  "more_keys": "more_values",
  "data": {
    "more_data": {
      "even_more_data": "snipped"
    }
  },
  "you_get_the": "idea"
}

Sorry for the inline comments messing up the data when copying & pasting, but that seems the best way to clarify my goal: For all root keys that end with /, I need the value of .type, so that the final result for the above example is token userpass.

I managed to create a working filter for the root keys:

host:~ user$ jq -r '. | keys[] | endswith("/")' <<< "${json_data}"
false
false
false
true
true
false

and I can use that filter to get only the wanted keys, but that is the keys alone and not the entire data structures underneath them:

host:~ user$ jq -r '. | keys[] | select(. | endswith("/"))' <<< "${json_data}"
token/
userpass/

I just can't seem to put this all together...

Can anyone help me ?

like image 724
ssc Avatar asked Feb 21 '18 11:02

ssc


People also ask

How do you filter jq?

jQuery filter() MethodThe filter() method returns elements that match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned.

What is jq slurp?

“Slurp” tells jq to read every line of the input JSON lines and treat the entire group as one huge array of objects. With the Twitter data still in the input box on jq play, check the “Slurp” box, and just put . in the filter.

Does jq have a function?

jQuery has() Method The has() method returns all elements that have one or more elements inside of them, that matches the specified selector. Tip: To select elements that have multiple elements inside of them, use comma (see example below).

What is the output of jq?

jq usually outputs non-ASCII Unicode codepoints as UTF-8, even if the input specified them as escape sequences (like "\u03bc"). Using this option, you can force jq to produce pure ASCII output with every non-ASCII character replaced with the equivalent escape sequence.


1 Answers

to_entries is worth knowing about, not least because it often leads to easy-to-read (variable-free) pipelines, as here:

to_entries[] | select(.key|endswith("/")) | .value.type
like image 110
peak Avatar answered Sep 21 '22 16:09

peak