我在file.json中有一个大型数据转储,如下所示:
[{
"recordList" : {
"record" : [{
"Production" : {
"creator.role" : {
"term" : "A"
}
}
},
{
"Production" : {}
},
{
"Production" : {
"creator.role" : {
"term" : ""
}
}
},
{
"Production" : [
{
"creator.role" : {"term" : "B"}
},
{
"creator.role" : {"term" : ""}
}
]
}]
}
}]
我需要检查记录中是否至少有一个"创建者角色"的"术语"(不为空(。如果有,我为 CSV 文件中的该字段提供 1 其他 0。
感谢之前帖子中的答案,我设法访问了一个字段"creator",尽管它可以是一个对象或数组(请参阅:使用 jq 访问可以是字符串或数组的字段(。
但是现在我对带有特殊字符".."的字段"creator.role"也有同样的问题,并且不知道如何处理。
我尝试的代码:
jq -r '.[].recordList.record[].Production | "(if ((type == "array" and .[0]["creator.role"].term and .[0]["creator.role"].term !="") or (type == "object" and ["creator.role"].term and ["creator.role"].term !="")) then 1 else 0 end),"' file.json
我收到此错误:
Cannot index array with string "term"
在这种情况下,我想得到的输出是:
1,
0,
0,
1,
jq
解决方案:
jq -r '.[].recordList.record[].Production
| "(if ((type == "array" and any(.["creator.role"].term !=""))
or (type == "object" and .["creator.role"].term and .["creator.role"].term !=""))
then 1 else 0 end),"' file.json