jq选择嵌套json bash中具有特定值的对象

时间:2017-06-29 18:27:00

标签: json bash jq

这是我的json。

[
 {
  "time": "2017-06-10 00:00:48-0400,317",
  "UserInfo": {
    "AppId": "ONE_SEARCH",
    "UsageGroupId": "92600",
   },
  "Items": [
    {
     "PublicationCode": "",
     "OpenUrlRefId": "",
     "ReferringUrl": "N",
     "OpenAccess": "0",
     "ItmId": "1328515516"
    }
   ]
 },
 {
  "time": "2017-06-10 00:00:48-0400,548",
  "UserInfo": {
    "AppId": "DIALOG",
    "UsageGroupId": "1195735",
  },
  "Items": [
    {
     "Origin": "Alert",
     "PublicationCode": "",
     "NumberOfCopies": 1,
     "ItmId": "1907446549"
    },
    {
     "Origin": "Alert",
     "PublicationCode": "",
     "NumberOfCopies": 1,
     "ItmId": "1907446950",
    }
  ]
 }
]

我想使用jq来提取具有" Origin":" Alert"在其元素"项目"。结果应如下所示:

{
 "time": "2017-06-10 00:00:48-0400,548",
 "UserInfo": {
   "AppId": "DIALOG",
   "UsageGroupId": "1195735",
},
 "Items": [
   {
    "Origin": "Alert",
    "PublicationCode": "",
    "NumberOfCopies": 1,
    "ItmId": "1907446549"
   },
   {
    "Origin": "Alert",
    "PublicationCode": "",
    "NumberOfCopies": 1,
    "ItmId": "1907446950",
   }
 ]
}

或者这个:

{
 "Items": [
    {
     "Origin": "Alert",
     "PublicationCode": "",
     "NumberOfCopies": 1,
     "ItmId": "1907446549",
     "ReasonCode": ""
    },
    {
     "Origin": "Alert",
     "PublicationCode": "",
     "NumberOfCopies": 1,
     "ItmId": "1907446950",
    }
 ]
}

如何使用jq做到这一点?我尝试了几种方法,但大多数方法只会返回一个包含所有子对象的数组,包括" Origin":#34; Alert"。我需要这些儿童对象仍然保留结构,因为我需要知道它们中的哪些发生在一起,哪些发生在一起。

BTW," Origin"的唯一价值。是"警报"。因此,如果您有任何方法来选择具有给定键名的对象,它也应该有效。

谢谢! :)

1 个答案:

答案 0 :(得分:2)

过滤器:

public abstract class BaseMaster<TChild> where TCHild : BaseChild
{
    // this probably doesn't have to be 'abstract' anymore
    public abstract ReadOnlyCollection<TChild> Children { get; }
}

public class FirstRealMaster : BaseMaster<FirstRealChild>
{
}

产生第一个提到的可接受结果。如果您的jq没有.[] | select( any(.Items[]; .Origin == "Alert")) ,那么我建议升级。如果这不是一个选项,那么您可以使用以下简单但非常低效的过滤器:

any/2

或者:

.[] | select( .Items | map(.Origin) | index("Alert"))