如何基于bash中的键从json中获取值
我试图使用jq从下面的json/test.json文件中提取分支的值如何基于bash中的键从json中获取值,json,jq,Json,Jq,我试图使用jq从下面的json/test.json文件中提取分支的值 { "pipeline": { "name": "test", "roleArn": "arn:aws:iam::1234:role/service-role/AWSCodePipelineServiceRole-us-west-2-test", "artifac
{
"pipeline": {
"name": "test",
"roleArn": "arn:aws:iam::1234:role/service-role/AWSCodePipelineServiceRole-us-west-2-test",
"artifactStore": {
"type": "S3"
},
"stages": [{
"name": "Source",
"actions": [{
"name": "Source",
"actionTypeId": {
"category": "Source",
"version": "1"
},
"runOrder": 1,
"configuration": {
"Branch": "experiment"
}
}]
}],
"version": 1
}
}
下面是我正在使用的jq命令
jq-r.pipeline.stages.actions.configuration.Branch'test.json
,它返回jq:error(在test.json:76):无法使用字符串“actions”对数组进行索引。我这里缺少了一些内容您的json密钥地址应该是.pipeline.stages[0]。actions[0].configuration.Branch
,使您的命令如下所示:
jq-r'.pipeline.stages[0].操作[0].配置.Branch'test.json
这是因为
阶段
和操作
都是数组,它们都只有一个项目。当您在执行查询时,如果一开始有些东西不起作用,请尝试一些简单的东西并不断添加到其中。所以在你的情况下,从
$ jq -r '.pipelines' test.json
null
啊哈,这是“管道”而不是“管道”,所以从这里开始:
$ jq -r '.pipeline' test.json
{
"name": "test",
"roleArn": "arn:aws:iam::1234:role/service-role/AWSCodePipelineServiceRole-us-west-2-test",
"artifactStore": {
"type": "S3"
},
"stages": [
{
"name": "Source",
"actions": [
{
"name": "Source",
"actionTypeId": {
"category": "Source",
"version": "1"
},
"runOrder": 1,
"configuration": {
"Branch": "experiment"
}
}
]
}
],
"version": 1
}
这样就行了。现在我们想进入“阶段”,所以我们这样做
$ jq -r '.pipeline.stages' test.json
[
{
"name": "Source",
"actions": [
{
"name": "Source",
"actionTypeId": {
"category": "Source",
"version": "1"
},
"runOrder": 1,
"configuration": {
"Branch": "experiment"
}
}
]
}
]
请注意,“stages”为您提供了一个数组,而不仅仅是一个散列,因此您必须引用第0个元素[0]
$ jq -r '.pipeline.stages[0]' test.json
{
"name": "Source",
"actions": [
{
"name": "Source",
"actionTypeId": {
"category": "Source",
"version": "1"
},
"runOrder": 1,
"configuration": {
"Branch": "experiment"
}
}
]
}
现在你可以开始“行动”
然后是第0个
$ jq -r '.pipeline.stages[0].actions[0]' test.json
{
"name": "Source",
"actionTypeId": {
"category": "Source",
"version": "1"
},
"runOrder": 1,
"configuration": {
"Branch": "experiment"
}
}
最后是配置和分支
$ jq -r '.pipeline.stages[0].actions[0].configuration.Branch' test.json
experiment
看起来第一个键是“pipeline”,但您的命令中有“pipeline”。@AndyLester我现在做了修改,它抛出了一个不同的错误,那是什么不同的错误?不要让我们猜。@AndyLester用新的错误更新了问题,应该不是
。pipeline.stages[0]。actions[0]。configuration.Branch
?因为操作
和阶段
都是数组
$ jq -r '.pipeline.stages[0].actions[0].configuration.Branch' test.json
experiment