我正在尝试查找具有主题且得分的人名。 但是我正在获取索引数组。 此问题与在Stackoverflow上提出的其他问题不同,因为它引发参数错误,该参数不在[]中,而在{}中
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"
我该如何解决此错误?
答案 0 :(得分:1)
$ jq -r '.[].result."*value*"[] | select(.Score.English) | "Name: \(.name)", "Subject: \(.Score.English)"' file
Name: ABC
Subject: A+
Name: CDE
Subject: A-
答案 1 :(得分:0)
EFG 得分的长度为0,可能无济于事:
"sessionId": "000001",
"name": "EFG",
"Age": "21",
"Score": {}
因此,在尝试评估时会感到窒息:
Subject: .result."*value*".Score.English
答案 2 :(得分:0)
这是一种替代解决方案,使用基于步行路径的Unix实用程序 jtc
:
如果您有这样的不规则JSON,并且想要确保仅显示name
个具有同级[Score][English]
记录的bash $ <file.json jtc -x'<name>l:[-1][Score][English]' -y'[-2][name]' -y'[-1][English]' -l
"name": "ABC"
"English": "A+"
"name": "CDE"
"English": "A-"
bash $
,那么这种查询将类似于:
"Subject"
编辑:如果需要"English"
代替... | sed -e 's/^"English/"Subject/g'
,则将输出通过管道传递到sed:
jtc
PS>披露:我是var a = db.server.find().sort({_id:-1}).limit(1)
工具的创建者