如何打印“游戏”、“玩具”、“书籍”之后的值?这是 jq '.' 的输出在文件上:
{ "reports": [ { "games": 3, "toys": 0, "books": 3, "to": "2017-07-22T00:00:00.000+0000", "from": "2017-07-21T00:00:00.000+0000", "eventType": "bookedIn", "rowName": "CWQ" }, { "games": 0, "toys": 0, "books": 0, "to": "2017-07-22T00:00:00.000+0000", "from": "2017-07-21T00:00:00.000+0000", "eventType": "bookedOut", "rowName": "AED" } ] }
我尝试过
{ 回显“[”;猫文件;回显“]”; } | jq -r ' .[] | ( "\n" + .rowName + ":", "游戏 -> " + (.games | tostring), "玩具 -> " + (.toys | tostring), "书籍 -> " + (.books | tostring) ))'
看来我做错了什么。
更新 据我所知,假设书籍还有另外两项:提供者和名称:-?
jq -r '.reports |
.[] |
("\n" + .rowName + ":",
"Games: " + (.games | tostring),
"Toys: " + (.toys | tostring),
.books | .[] |
("\n" + .name + ": ",
"provider: " + (.provider | tostring) ) )
' response.json
我会得到 jq: error (at response.json:1): Cannot iterate over null (null)
答案1
使用 JSON 命令行解析器jq
:
$ jq -r '.reports[] |
"\(.rowName) :",
"books -> \(.books)",
"toys -> \(.toys)",
"games -> \(.games)\n"' input.json
CWQ:
books -> 3
toys -> 0
games -> 3
AED:
books -> 0
toys -> 0
games -> 0
注意:这使用jq
的字符串插值并迭代数组中的所有条目reports
,挑选出相关信息。
更新:处理.books
对象数组:
给定
{
"reports": [
{
"games": 3,
"toys": 0,
"books": [
{
"provider": "The provider",
"name": "The name"
}
],
"to": "2017-07-22T00:00:00.000+0000",
"from": "2017-07-21T00:00:00.000+0000",
"eventType": "bookedIn",
"rowName": "CWQ"
},
{
"games": 0,
"toys": 0,
"books": [
{
"provider": "The 1st provider",
"name": "The 1st name"
},
{
"provider": "The 2nd provider",
"name": "The 2nd name"
}
],
"to": "2017-07-22T00:00:00.000+0000",
"from": "2017-07-21T00:00:00.000+0000",
"eventType": "bookedOut",
"rowName": "AED"
}
]
}
我们可以简单地做
$ jq -r '.reports[] |
"\(.rowName):",
( .books[] | "book name -> \(.name)",
"book provider -> \(.provider)" ),
"toys -> \(.toys)",
"games -> \(.games)\n"'
CWQ:
book name -> The name
book provider -> The provider
toys -> 0
games -> 3
AED:
book name -> The 1st name
book provider -> The 1st provider
book name -> The 2nd name
book provider -> The 2nd provider
toys -> 0
games -> 0
答案2
awk -v RS='[{},]' '/^"(games|toys|books)"/{ sub("^.*:",""); print; }' file
0
0
0
50
30
20
10
30
20
或者只用一个词:
awk -v pattern=games -v RS='[{},]' '$0 ~ "^\"" pattern "\"" { sub("^.*:",""); print; }' file
0
50
10
答案3
让我们用 JSON 解析器解析该 JSON,杰克。
jq -r '
.reports |
.[] |
(
"\n" + .rowName + ":",
"games -> " + (.games | tostring),
"toys -> " + (.toys | tostring),
"books -> " + (.books | tostring)
)
' file
CWQ:
games -> 3
toys -> 0
books -> 3
AED:
games -> 0
toys -> 0
books -> 0