I'm trying to use jq parser in my bash scripts and I'm confused about how it works, could someone explain what am I doing wrong?

Here is the original file from the external service and I need to get value from it:

root@test ~ # cat test.json 

Trying to send it to jq:

root@test ~ # cat narod.json | jq
  "sensors": [
      "id": 34585,
      "value": -3.06,
      "time": 1457031003

Trying to get sensors:

root@test ~ # cat narod.json | jq '.sensors'
    "id": 34585,
    "value": -3.06,
    "time": 1457031003

Trying to get value from sensors:

root@test ~ # cat narod.json | jq '.sensors.value'
jq: error (at <stdin>:0): Cannot index array with string "value"
  • Try jq sensors[].value not at my computer so can't test or post a full answer but will do later – Phil Mar 4 '16 at 5:33
  • It works! Thanks a lot and could you explain or give me a link where I was wrong? – SimWhite Mar 4 '16 at 5:40
  • 1
    .sensors in your JSON input is an array, not a dict. It doesn't have indexes like .value – only its inner items do. So you need to tell jq to apply the index to each item of the array using [] – user1686 Mar 4 '16 at 5:54

As discussed in the comments, in this specific case you should use:

jq sensors[].value

This is because you need to tell jq to expect an array (denoted by the [ ]). Effectively this is saying, 'search at the next level down in the hierarchy.'

In general, when you encounter an array ([) in your json file you should provide this in your query: jq array_name[].object_in_array would return the contents of object_in_array.


Something to keep in mind when working with arrays in jq is that the [] operator will enumerate each of the array's values, so


returns the .value of all objects in .sensors. It is equivalent to the filter

   .["sensors"]    # choose value of "sensors" key
 | .[]             # enumerate each value
 | .["value"]      # choose value of "value" key

should you want the .value for a particular object often you'll want to include a select. e.g.

 .sensors[] | select(.id == 34585) | .value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.