Blooze
Blooze

Reputation: 2267

Beginner parsing with jq - Cannot index array with string

Here is a snippet of the output when I do a basic jq, what I want to get is the data of the partitions.

jq .



[
 {
"partitions": [
  "name@website
],
"os_pid": "20458",
"fd_used": 20,
"fd_total": 1024,
"sockets_used": 2,
"sockets_total": 829,
"mem_used": 41128152,

When I do jq '.partitions' I get Cannot index array with string "partitions" - Any thoughts as to why that happens?

Upvotes: 1

Views: 7819

Answers (1)

that other guy
that other guy

Reputation: 123560

You have an array, where each element has a partitions field. You ask to get "partitions", but you don't say from which element or elements in the array.

Here's a complete, self-contained file:

[
  {
    "partitions": [ "name@website" ]
  },
  {
    "partitions": [ "more" ]
  }
]

Your expression produces the error you say:

$ jq '.partitions' file
jq: error (at file:8): Cannot index array with string "partitions"

You can get "partitions" for the first element:

$ jq '.[0].partitions' file
[
  "name@website"
]

Or for each elements:

$ jq '.[].partitions' file
[
  "name@website"
]
[
  "more"
]

Or join all the partitions from each element into one list:

$ jq 'map(.partitions) | add' file
[
  "name@website",
  "more"
]

Upvotes: 2

Related Questions