3

I have data structured like this:

{
  "data": {
    "2017-06-20": {
      "shifts": [
        {
          "id": 24,
          "shift_request_id": 24,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 38,
          "shift_request_id": 38,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 85,
          "shift_request_id": 85,
          "created_at": "2017-06-27 15:10:51",
          "updated_at": "2017-06-27 15:10:51"
        }
      ]
    },
    ...
    ...
    ...
    ...
    "2017-06-21": {
      "shifts": [
        {
          "id": 26,
          "shift_request_id": 26,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 28,
          "shift_request_id": 28,
          "created_at": "2017-06-27 15:10:50",
          "updated_at": "2017-06-27 15:10:50"
        },
        {
          "id": 88,
          "shift_request_id": 88,
          "created_at": "2017-06-27 15:10:51",
          "updated_at": "2017-06-27 15:10:51"
        }
      ]
    }
  }
}

So, with those date-like formatted keys, let's say I want to extract shifts from say, first such a key. I am not interested in extracting by particular date as that would be easy as specifying that date as a key, but rather selecting from the whole set, one of them or range, by numeric index, once obtained those keys.

I tried:

jq '.[] | keys'

which gives me an array of all keys, but then I don't know how would I extract array of shifts for a particular key indexed by number.

jq '.[] | keys[3]'

will give me the 4th key in a row, but then .shifts won't work on that, saying that it Cannot index string with string "shifts"

branquito
  • 3,864
  • 5
  • 35
  • 60

1 Answers1

3

By looking at this https://stackoverflow.com/a/34227629/2434479, I was able to find my way around this problem, so I will keep it here as a reference for someone who might find him self in a similar situation.

So one way of doing it would be:

❯ http ... | jq '.[] | to_entries[] | [.key, (.value.shifts | length)] | @csv'

And when specific key by index needed, say 4th in row:

❯ http|curl ... | jq '.[] | keys_unsorted[3] as $k | "\($k), \(.[$k].shifts | length)"'
branquito
  • 3,864
  • 5
  • 35
  • 60