我正在尝试查找有主题和分数的人名。但我得到的是索引数组。
jq -r '.[] | select(.result."*value*".Score.English) | {Name: .result."*value*".name, Subject: .result."*value*".Score.English} | @text' test.txt | sed 's/^{\|}$//g; s/,/\n/'
输入 JSON 文件
[{
"host": "testserver",
"hostclass": "Unknown",
"result": {
"*value*": [
{
"sessionId": "000001",
"name": "ABC",
"Age": "21",
"Score": {
"English": "A+",
"Mathematics": "B-",
"String Theory": "C+"
}
},
{
"sessionId": "000001",
"name": "CDE",
"Age": "21",
"Score": {
"English": "A-",
"German": "B-",
"French": "C+"
}
},
{
"sessionId": "000001",
"name": "EFG",
"Age": "21",
"Score": {
}
},
{
"sessionId": "000001",
"name": "XYZ",
"Age": "21"
}]
}
}]
输出 :
Name: ABC
Subject : A+
Name: CDE
Subject : A-
错误 :
jq: error (at test.txt:39): Cannot index array with string "Score"
我该如何修复这个错误
答案1
您需要使用 来迭代"*value*"
子元素"*value*"[]
。这是我测试过的解决方案,它会产生您想要的输出:
cat test.txt | jq -r '.[].result."*value*"[] | select(.Score.English) | "Name: "+.name+"\nSubject: "+.Score.English'
答案2
我很惊讶到目前为止没有人给你一个 jq 解决方案。那么,让我给你一个替代方案——基于 unix walk-path 实用程序jtc
:
bash $ <input.json jtc -w'<English>l:[-2][name]' -w'<English>l:' -l
"name": "ABC"
"English": "A+"
"name": "CDE"
"English": "A-"
bash $
如果你确实想用 替换"English"
,"Subject"
那么每次行走时都要添加模板,如下所示:
bash $ <input.json jtc -w'<English>l:[-2][name]' -w'<English>l:' -TT -T'{"Subject":"{}"}' -ll
"name": "ABC"
"Subject": "A+"
"name": "CDE"
"Subject": "A-"
bash $
- 第一个模板(
-TT
)是虚拟的,注定会失败(因为第一次行走不需要改变)
顺便说一句,还有一种更简洁的方式来编写相同的查询:
<input.json jtc -x'<English>l' -y:[-2][name] -y: -TT -T'{"Subject":"{}"}' -ll
jtc
PS> 披露:我是JSON 操作 shell cli 工具的创建者
编辑:实现相同查询的另一种方法:
bash $ <input.json jtc -w'<English>l:<N>v[-2][name]' -llT'{"Name":{{}},"Subject":{{N}}}'
"Name": "ABC"
"Subject": "A+"
"Name": "CDE"
"Subject": "A-"
bash $