10

I have the following structure (full file example here):

{
  {
    "weather": [
      {
        "advertiser": "Worldwide Forecasts",
        "notificationText": "Weather - Check the Weather Now - Weather",
        "notificationURL": "http://www.worldwideforecasts.com/b/index.html?aff_sub=NL01R15178755321634q5X2zHqXo1976US&utm_term=weather&utm_campaign=bing&utm_content=new-weather%20-%20Weather%20-%202&utm_medium=Search_SEM&utm_source=7&nlhash=BR6et8ISl5dCdAHF&requestId=NL01R15178755321634q5X2zHqXo1976US",
        "uuid": "9f27d258-f9d5-4b19-9f70-291eb9cbab51",
        "creativeSetId": "2799cbab-1fa1-4f15-bbc9-c92381dbfc57"
      },
      {
        "advertiser": "Worldwide Forecasts",
        "notificationText": "Weather - Check the Weather Now - Weather",
        "notificationURL": "http://www.worldwideforecasts.com/b/index.html?aff_sub=NL01R15178755321634q5X2zHqXo1976US&utm_term=weather&utm_campaign=bing&utm_content=new-weather%20-%20Weather%20-%202&utm_medium=Search_SEM&utm_source=7&nlhash=BR6et8ISl5dCdAHF&requestId=NL01R15178755321634q5X2zHqXo1976US",
        "uuid": "9f27d258-f9d5-4b19-9f70-291eb9cbab51",
        "creativeSetId": "2799cbab-1fa1-4f15-bbc9-c92381dbfc57"
      }
    ]
  }
}

With several categories like the weather example.

I want to use jq to get a list of all values for notificationURL so that I'm left with a list of the URLs for all advertisers.

I was initially thinking I could do something like:

cat file.json | jq .[].[].notificationURL

But this doesn't work.

1 Answer 1

12

You have two basic options here (with your full file):

jq '.categories[][].notificationURL' bundle.json
jq '.categories[] | .[].notificationURL' bundle.json

In the first, you apply the [] operation twice in succession, and in the second you compose two separate filters together with the pipe operator. I find using extra pipes a lot easier to work with and debug, but these are both identical for your purpose.

.[] generic iteration always applies to the single input value of this iteration, so it has to be the first element in an expression and is a syntax error anywhere else, but [] applied to a specific value to its left-hand side is fine anywhere.

The very fact that you can write abc[] at all, rather than only .[], is not well-described in the jq documentation, but you can. You can think of .[] as applying [] to the identity filter ., although I think it is actually a special case.


In this exact case you can shrink it down to:

jq '.[][][].notificationURL' bundle.json

which applies the iterator operation thrice in a row, since there's only the one key "categories" in the top-level object.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .