Miss Alena
Miss Alena

Reputation: 735

getting all the values of an array with jq

I parse a json file with jq:

jq .response[1].text file.json

It works fine, but each time I have to enter the number .response[2].text, .response[3].text etc. I want to get all the values at once (200 values)

But when I do:

jq .response[].text file.json

It gives an error: Cannot index number with string "text"

The file looks like this:

{
  "response": [
    1000,
    {
      "id": ,
      "date": ,
      "owner_id": ,
      "from_id": ,
      "post_type": "post",
      "text": "blabla",
      "attachment": {
        "type": "photo",
        "photo": {
          "pid": ,
          "aid": -7,
          "owner_id": 
        }
      },
      "attachments": [
        {
          "type": "photo",
          "photo": {
          }
        },
        {
          "type": "link",
          "link": {
            "url": "",
            "title": "",
            "description": "",
            "target": "external"
          }
        }
      ],
      "post_source": {
        "type": "vk"
      },
      "comments": {
        "count": 0,
        "groups_can_post": true,
        "can_post": 1
      },
    },
    {
      "id": ,
      "date": ,
      "owner_id": ,
      "from_id": ,
      "post_type": "post",
      "text":    "blabla",
      "attachment": {
        "type": "link",
        "link": {
          "url": "",
          "title": "",
          "description": "",
          "target": "external",
          "
        }

Upvotes: 73

Views: 154414

Answers (1)

peak
peak

Reputation: 116640

Evidently one of the items in the array is a string. If your jq supports "?", then one possibility would be to use it:

.response[].text?

Another would be to check the type explicitly, e.g.:

.response[] | objects | .text

Yet another possibility:

.response[] | select(type=="object" and has("text")) | .text

If you want to have a placeholder value when there is no "text" field:

 .response[] | if type=="object" and has("text") then .text else null end

So it really depends on your requirements and perhaps the version of jq that you are using.

Upvotes: 99

Related Questions