如何使用jq通过元素属性值过滤对象数组? [英] How to filter array of objects by element property values using jq?

查看:102
本文介绍了如何使用jq通过元素属性值过滤对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢使用 jq 来过滤json文件:

I like to filter json files using jq:

jq . some.json

给出包含对象数组的json:

Given the json containing an array of objects:

{
  "theList": [
    {
      "id": 1,
      "name": "Horst"
    },
    {
      "id": 2,
      "name": "Fritz"
    },
    {
      "id": 3,
      "name": "Walter"
    },
    {
      "id": 4,
      "name": "Gerhart"
    },
    {
      "id": 5,
      "name": "Harmut"
    }
  ]
}

我想过滤该列表以仅显示id分别为2和4的元素,因此预期的输出为:

I want to filter that list to only show the elements with id having the value 2 and 4, so the expected output is:

{
  "id": 2,
  "name": "Fritz"
},
{
  "id": 4,
  "name": "Gerhart"
}

如何使用jq过滤json?我玩过select和map,但是没有任何东西可以工作,例如:

How do I filter the json using jq? I have played around with select and map, yet didn't got any of those to work, e.g.:

$ jq '.theList[] | select(.id == 2) or select(.id == 4)' array.json
true

推荐答案

来自文档:

jq '.[] | select(.id == "second")' 

输入 [{"id": "first", "val": 1}, {"id": "second", "val": 2}]

输出 {"id": "second", "val": 2}

我认为您可以执行以下操作:

I think you can do something like this:

jq '.theList[] | select(.id == 2 or .id == 4)' array.json

这篇关于如何使用jq通过元素属性值过滤对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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