如何基于条件过滤JSON对象,然后使用JQ解析器从过滤对象中选择几个键

如何基于条件过滤JSON对象,然后使用JQ解析器从过滤对象中选择几个键,json,jq,Json,Jq,我有一个低于JSON的结构,它有一个对象数组 { "payload": { "location": { "uid": 1, "type": "foo" }, "name": "foo", "maxResults": 10 }, "product": { "uid": "1232323", "source": "foo", "service": "pricing", "version": "0.1

我有一个低于JSON的结构,它有一个对象数组

 {
  "payload": {
    "location": {
      "uid": 1,
      "type": "foo"
    },
    "name": "foo",
    "maxResults": 10
  },
  "product": {
    "uid": "1232323",
    "source": "foo",
    "service": "pricing",
    "version": "0.1",
    "time": 1507602150899,
    "type": "mobile",
    "id": 1
  }
}
{
  "payload": {
    "location": {
      "uid": 2,
      "type": "bar"
    },
    "name": "bar",
    "maxResults": 10
  },
  "product": {
    "uid": "244434242",
    "source": "bar",
    "service": "pricing",
    "version": "0.2",
    "time": "1507602ds0899",
    "type": "phone",
    "id": 2
  }
}
我想根据条件过滤对象,其中
product.type==mobile
,然后在匹配对象中,我只想过滤
id
service
字段。所以在上面的例子中,下面是O/P

{
  "service" : "pricing",
  "id" : 1
}
我能够使用

cat myjson.json | jq 'select(.product.type == "moble")' 

但是在那之后,我怎样才能只过滤对象的
服务
id
字段呢?

也许这会帮助您:

map(select(.product.type == "mobile")) | .[] | {id: .product.id, service: .product.service}

问题中当前显示的数据并不是严格意义上的JSON,但是由于OP提到输入应该是一个数组,下面假设数据是对象的JSON数组

一个简洁的解决方案是:

data[] | .product | select(.type == "mobile") | {service, id}
通过如上所述调整输入数据,输出将如图所示,即:

{"service":"pricing","id":1}

我想使用
jq
解析器。您的
JSON
输入在语法上不正确,请复制并粘贴它,然后查看详细信息yourself@Inian,这很好,正如我所说,使用
cat myjson.json | jq'select(.product.type==“moble”)
,我能够获得与我的条件匹配的对象。,JQ很好用。您在
moble
中有一个输入错误,除非json被修复,
JQ
无法解析it@Inian,是的,这是一个输入错误,但是为什么我首先要得到O/P?@Inian,谢谢,我只是在更新我的JSON。请在几秒钟后检查,并建议如何从对象中仅获取几个值。