使用jq解析json数据时获取父元素ID

时间:2018-07-05 06:22:12

标签: json jq

我想在子元素值为JSON数据中的client_release时打印父元素的ID。

如果     data.properties.value ==“ client_release”

则输出应为

abcd1g2f,hirk5d7b3l

我在下面尝试过,但是没有运气

jq '.data[].properties[]|select(.value=="client_release")|.id'

JSON数据如下:

{  
   "data":[  
      {  
         "id":"abcd1g2f",
         "resourceURI":"https://somerepo.com/service/local/privileges/abcd1g2f",
         "name":"release1",
         "description":"release1",
         "type":"target",
         "userManaged":true,
         "properties":[  
            {  
               "key":"repositoryGroupId",
               "value":""
            },
            {  
               "key":"method",
               "value":"create,read"
            },
            {  
               "key":"repositoryId",
               "value":"client_release"
            },
            {  
               "key":"repositoryTargetId",
               "value":"1"
            }
         ]
      },
      {  
         "id":"asdf1k4g",
         "resourceURI":"https://somerepo.com/service/local/privileges/asdf1k4g",
         "name":"release2",
         "description":"release2",
         "type":"target",
         "userManaged":true,
         "properties":[  
            {  
               "key":"repositoryGroupId",
               "value":""
            },
            {  
               "key":"method",
               "value":"read"
            },
            {  
               "key":"repositoryId",
               "value":"formal_release"
            },
            {  
               "key":"repositoryTargetId",
               "value":"1"
            }
         ]
      },
      {  
         "id":"hirk5d7b3l",
         "resourceURI":"https://somerepo.com/service/local/privileges/hirk5d7b3l",
         "name":"release3",
         "description":"release3",
         "type":"target",
         "userManaged":true,
         "properties":[  
            {  
               "key":"repositoryGroupId",
               "value":""
            },
            {  
               "key":"method",
               "value":"create,read"
            },
            {  
               "key":"repositoryId",
               "value":"client_release"
            },
            {  
               "key":"repositoryTargetId",
               "value":"1"
            }
         ]
      }
   ]
}

2 个答案:

答案 0 :(得分:2)

以下过滤器可避免重复,并且可能比使用select(.properties []。value ...)更为有效:

.data
| map(select(.properties | any(.[]; .value == "client_release")) | .id)
| join(",")

(如果希望将.id的值作为JSON字符串,则可以在末尾使用@csv。)

“ repositoryId”

如果仅关注与“ repositoryId”相对应的值,则可以 使用from_entries,例如:

.data
| map(select(.properties | from_entries.repositoryId == "client_release") | .id)
| join(",")

答案 1 :(得分:1)

这个想法是正确的,但是data[]数组应该在select语句之外,

jq '.data[] | select(.properties[].value == "client_release") | .id'

要按照问题中的指示将其放入CSV格式,请将结果放入数组中并使用@csv构造

jq --raw-output '[.data[] | select(.properties[].value == "client_release") | .id] | @csv'