我在json文件中更改子字段的值时遇到了困难。json文件是一个jira问题字段的提取(其中一些字段)。
下面是我的json的一个子集的结构:
{
"fields": {
"summary": "",
"issuetype": {
"self": "",
"id": "",
"description": "",
"iconUrl": "",
"name": "",
"subtask": true,
"avatarId": 17116
}
}
}
我可以使用以下命令重新分配像summary
这样的字段:
jq --arg field "$field" --arg value "$value" '.fields[$field] = $value' issue_fields.json > tmp.json && mv tmp.json issue_fields.json
但是我在issuetype
字段中更改像name
这样的子字段时遇到了麻烦。
jq --arg field "$field" --arg value "$value" --arg subfield "$subfield" '.fields[$field][$subfield] = $value' issue_fields.json > tmp.json && mv tmp.json issue_fields.json
我总是遇到这样的错误:Cannot index array with string "name"
1条答案
按热度按时间wooyq4lh1#
看看你的代码,一切看起来都很好,但正如knittl提到的,你可能有你的值设置不正确。当我第一次学习json和jq时,我挣扎着学习语法,因为它可能是喜怒无常的,直到你摸索到模式(我仍然没有完全-大多数都没有哈哈)。幸运的是,
man jq
有很多好的信息,互联网上有一些很棒的教程。通过您提供的内容,我能够获得预期的结果-这里我想将
summary
字段更改为“hello world”,因此我设置了以下值:当我跑的时候,我得到了预期的结果:
当我想修改
issuetype
字段下的一个子字段时也是如此运行列出的修改子字段的命令,我得到了预期的结果。
输出:
如果变量设置不正确,我能够重现你的错误。想知道你是否忘记将
field
变量设置为issuetype
,(也许它仍然设置为summary
,从第一个命令,你正在搞乱)..(使用set -x
之前的命令,以查看更多的调试,键入set +x
后,以禁用额外的调试):为了确保没有误导您,我精心制作了一个示例脚本,它使用case语句来确定是否要更改
summary
字段或issuetype
下的子字段,并运行相应的命令。myscript.sh内容:
示例用法:
使用上面的方法,摆弄一下东西,把它弄到你想要的地方。
您还可以使用
bash -x myscript.sh
运行它,以查看调试输出,从而更直观地了解它是如何工作的。