如何使用 shell 脚本从 json 响应中提取值

如何使用 shell 脚本从 json 响应中提取值
{"expand":"renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations","id":"15114","self":"https://brg-jira-tst.state.mi.us/rest/api/2/issue/15114","key":"BRGTEST-11","fields":{"issuetype":{"self":"https://brg-jira-tst.state.mi.us/rest/api/2/issuetype/10200","id":"10200","description":"A task that needs to be done associated with Bridges project","iconUrl":"https://brg-jira-tst.state.mi.us/secure/viewavatar?size=xsmall&avatarId=10318&avatarType=issuetype","name":"Task","subtask":false,"avatarId":10318},"customfield_11500":"QAT"}}

上面是我的 json 响应,它存储在 a.json 中

我想使用 shell 脚本从 a.json 响应中提取 customfield_11500 的值。怎么做

在这种情况下,我的 shell 命令的输出必须给出“QAT”结果


针对滚动厌恶的格式化 JSON:

{
  "expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
  "id": "15114",
  "self": "https://brg-jira-tst.state.mi.us/rest/api/2/issue/15114",
  "key": "BRGTEST-11",
  "fields": {
    "issuetype": {
      "self": "https://brg-jira-tst.state.mi.us/rest/api/2/issuetype/10200",
      "id": "10200",
      "description": "A task that needs to be done associated with Bridges project",
      "iconUrl": "https://brg-jira-tst.state.mi.us/secure/viewavatar?size=xsmall&avatarId=10318&avatarType=issuetype",
      "name": "Task",
      "subtask": false,
      "avatarId": 10318
    },
    "customfield_11500": "QAT"
  }
}

答案1

对于最新版本的ksh93shell(v-或更高版本):

read -m json j < file.json &&
  print -r -- "${j.fields.customfield_11500}"

或者使用广泛可用的(尽管默认情况下通常不安装)jqjson 处理器工具:

jq -r '.fields.customfield_11500' file.json

答案2

以此为基础邮政 并使用格式化的json文件

grep -oP '(?<="customfield_11500": ")[^"]*' a.json

答案3

这是一个基于的简单替代解决方案jtc:

bash $ cat a.json | jtc -w'<customfield_11500>l'
"QAT"
bash $ 

JSON 结构必须仅由 JSON 感知例程处理(否则误报将不可避免)

相关内容