如何在jq中将迭代拆分为新行

时间:2018-07-31 15:20:01

标签: json bash jq

[注意:问题已经根据评论进行了澄清,因此其中一些可能已过时。]

我正在使用jq解析以下JSON:

[{
    "type": "A",
    "id": "A",
    "name": "A",
    "message": "OK",
    "updateDate": "2018-07-31T10:55:14.813Z",
    "createDate": "2018-07-31T08:01:32.164Z",
    "status": "ACTIVE"
}, {
    "type": "B",
    "id": "B",
    "name": "B",
    "message": "OK",
    "updateDate": "2018-07-31T10:55:16.803Z",
    "createDate": "2018-07-31T08:01:34.171Z",
    "status": "ACTIVE"
}, {
    "type": "C",
    "id": "C",
    "name": "C",
    "message": "OK",
    "updateDate": "2018-07-31T10:55:18.607Z",
    "createDate": "2018-07-31T08:01:37.181Z",
    "status": "ACTIVE"
}, {
    "type": "D",
    "id": "D",
    "name": "D",
    "message": "OK",
    "updateDate": "2018-07-31T10:55:20.877Z",
    "createDate": "2018-07-31T08:01:38.185Z",
    "status": "ACTIVE"
}, {
    "type": "E",
    "id": "E",
    "name": "E",
    "message": "OK",
    "updateDate": "2018-07-31T10:55:18.615Z",
    "createDate": "2018-07-31T08:01:44.207Z",
    "status": "ACTIVE"
}, {
    "type": "F",
    "id": "F",
    "name": "F",
    "message": "OK",
    "updateDate": "2018-07-31T10:55:19.131Z",
    "createDate": "2018-07-31T08:01:44.207Z",
    "status": "ACTIVE"
}, {
    "type": "G",
    "id": "G",
    "name": "G",
    "message": "OK",
    "updateDate": "2018-07-31T10:55:18.326Z",
    "createDate": "2018-07-31T08:01:46.212Z",
    "status": "ACTIVE"
}]

要显示名称和状态,我使用以下命令,其中$input保存上述JSON:

output=$(jq '.[] | "\(.name) \(.status)"' <<< "$input")
echo $output

这将产生:

"A: ACTIVE" "B: ACTIVE" "C: ACTIVE" "D: ACTIVE" "E: ACTIVE" "F: ACTIVE" "G: ACTIVE"

如何确保每次迭代都产生一条新行,如下所示:

      "A: ACTIVE"
      "B: ACTIVE"
      "C: ACTIVE" 
      "D: ACTIVE
      "E: ACTIVE"
      "F: ACTIVE"
      "G: ACTIVE"

1 个答案:

答案 0 :(得分:1)

[编辑:此答复已根据问题的澄清进行了修订。]

使用:

echo "$output"

如果您的bashmapfile,则可能值得考虑将output创建为bash数组:

mapfile -t output < <(jq  '.[] | "\(.name) \(.status)"' <<< "$input" )
printf "%s\n" "${output[@]}"