![](/img/trans.png)
[英]Convert text file with key=value pair to specific json format in jq
[英]Use jq to grab specific key:value pair from nth object in a JSON array
使用通過curl從Jenkins構建api調用中獲取的JSON
{
"_class" : "org.jenkinsci.plugins.workflow.job.WorkflowRun",
"actions" : [
{
"_class" : "hudson.model.CauseAction",
"causes" : [
{
"_class" : "jenkins.branch.BranchIndexingCause",
"shortDescription" : "Branch indexing"
}
]
},
{
"_class" : "hudson.model.ParametersAction",
"parameters" : [ "..." ]
},
{
"_class" : "hudson.tasks.junit.TestResultAction",
"failCount" : 1,
"skipCount" : 14,
"totalCount" : 222,
"urlName" : "testReport"
}
],
"artifacts" : [ "..." ],
"result" : "UNSTABLE",
"previousBuild" : {
"number" : 98,
"url" : "<some Url>"
}
}
為什么我可以做jq '{result}' <fileNameWithJSON>
並得到
{ "result" : "UNSTABLE" }
但是我無法執行jq '{.actions[2] failCount}' <fileNameWithJSON>
或其他變體,例如
jq '{actions[2].failCount}'
jq '{actions[2] failCount}'
jq '{actions .[2].failCount}'
等等
得到{ "failCount" : "1" }
?
我想要獲取result
以及actions[2] failCount
, actions[2] skipCount
和actions[2] totalCount
來創建一個新的JSON,如下所示:
{ "result" : "UNSTABLE","failCount" : 1, "skipCount" : 14,"totalCount" : 222}
編輯:
我的目標是不必在api中更改密鑰時重新指定密鑰。 我基本上不想要這樣:
{result, "failCount":.actions[2].failCount, "skipCount":.actions[2].skipCount, "totalCount": .actions[2].totalCount}
jq只能將對象文字中的直接字段從一個對象復制到另一個對象。 盡管在支持這種功能的其他語言中最有可能做到這一點,但並未對其進行編程。
如果您的目標是最大程度地減少屬性名稱的重復,則只需重寫過濾器即可。
{result} + (.actions[2] | {failCount,skipCount,totalCount})
{}
語法是糖。 當您需要一個簡單的表達式時,它打算用作快捷方式,但是當您真正想要的更有趣時,沒有理由使用相同的縮短語法。
jq '
.actions[2] as $a2 | # assign second action to a variable
{ "result": .result, # refer direct to original input when appropriate...
"skipCount": $a2.skipCount, # ...or to that variable otherwise.
"failCount": $a2.failCount,
"totalCount": $a2.totalCount}
' <<<"$json"
我的目標是不必在api中更改密鑰時重新指定密鑰。
如果這是主要目標之一,則可能需要考慮以下示例,該方法也不假設.actions
哪個元素包含感興趣的信息:
{ result } + (.actions[] | select(has("failCount")))
使用您的示例數據,將產生:
{
"result": "UNSTABLE",
"_class": "hudson.tasks.junit.TestResultAction",
"failCount": 1,
"skipCount": 14,
"totalCount": 222,
"urlName": "testReport"
}
如果您不想要某些額外的字段,則可以將其刪除,例如,如果您絕對不希望使用“ _class”,則可以將del(._class)
添加到管道中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.