0stone0
0stone0

Reputation: 43972

jq Recursive search values by key, starting with

TL;DR

What is 's equivalent to grep '"\/v6' in the following command;

jq '.. .pattern? // empty' /tmp/all.json | grep '"\/v6'

Consider the following json;

{
  "payload": {
    "groups": [
      {
        "pattern": "/v6/",
        "groups": [
          {
            "pattern": "something/",
            "groups": [
              {
                "pattern": "somethingElse/",
                "groups": [
                  {
                    "pattern": "{specialPattern:[0-9]+}/",
                    "groups": [],
                    "routes": [
                      {
                        "type": "variable",
                        "pattern": "/v6/notImportant/{specialPattern:[0-9]+}/",
                        "methods": {

The json file is quite large, with a lot of irrelevant data

I'm trying to capture all the .pattern in the json file, based on this question I've created the following jq command:

jq '.. .pattern? // empty' /tmp/all.json

This works as expected, creating a output similar to this;

"/v6/"
"something/"
"somethingElse/"
"{specialPattern:[0-9]+}/"
"/v6/notImportant/{specialPattern:[0-9]+}/"

Question: How would I only select each .pattern that starts with /v6/ ? I've used like so

jq '.. .pattern? // empty' /tmp/all.json | grep '"\/v6'

However, there must be a jq-only solution to this.


Google taught me about jq's contains that seems to be the answer on some-sort-of related question;

Unfortunately I can't manage to make it work with my situation, since using select seems unnecessary.

Upvotes: 3

Views: 2811

Answers (1)

peak
peak

Reputation: 116730

To perform the selection, you could use

select( test( "^/v6/" ) )

So the command becomes;

jq '.. .pattern? // empty | select(test("^/v6/"))' /tmp/all.json

Or similarly with startswith.

Upvotes: 3

Related Questions