使用jq获取数组中的所有值

65

我使用jq解析一个JSON文件:

jq .response[1].text file.json

它能正常工作,但每次我都需要输入.number[2].text、.response[3].text等数字。我希望一次获取所有的值(200个值)。

但是当我这样做时:

jq .response[].text file.json

出现错误:无法使用字符串“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",
          "
        }

你能提供一下 file.json 的简短示例吗?另外,你使用的是哪个版本的 jq?我无法在 jq 1.5 和我认为是 file.json 示例的情况下重现错误。 - chepner
我已经添加了上面的示例。我的 jq 版本是 1.5。 - Miss Alena
response[0] 不是一个对象,而是一个数字。 - chepner
1个回答

88

显然,数组中的某个项是一个字符串。如果你的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?

另一种方法是显式地检查类型,例如:

.response[] | objects | .text

另一种可能性:

.response[] | select(type=="object" and has("text")) | .text
如果您希望在没有“文本”字段时使用占位符,请使用以下代码:
 .response[] | if type=="object" and has("text") then .text else null end
所以这真的取决于您的要求,也许取决于您使用的 jq 版本。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接