用jq获取数组的所有值 [英] getting all the values of an array with jq

查看:139
本文介绍了用jq获取数组的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用jq解析json文件:

I parse a json file with jq:

jq .response[1].text file.json

它工作正常,但是每次我必须输入数字.response [2] .text,.response [3] .text等.我想一次获取所有值(200个值)

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)

但是当我这样做时:

jq .response[].text file.json

出现错误:无法使用字符串"text"索引数字

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

文件如下:

{
  "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",
          "
        }

推荐答案

显然,数组中的一项是字符串.如果您的jq支持?",则可能使用它:

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

还有另一种可能性:

.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

因此,这实际上取决于您的要求以及您所使用的jq的版本.

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

这篇关于用jq获取数组的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆