Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting all the values of an array with jq

Tags:

json

parsing

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",
          "
        }
like image 283
Miss Alena Avatar asked Aug 05 '17 15:08

Miss Alena


1 Answers

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.

like image 144
peak Avatar answered Nov 02 '22 02:11

peak