用jq访问包含特殊字符的字段,该字段可以是对象或数组 [英] Accessing field with jq that contains a special character and can be an object or an array
问题描述
我在file.json中有大量数据转储,如下所示:
I have a large dump of data in a file.json that looks like:
[{
"recordList" : {
"record" : [{
"Production" : {
"creator.role" : {
"term" : "A"
}
}
},
{
"Production" : {}
},
{
"Production" : {
"creator.role" : {
"term" : ""
}
}
},
{
"Production" : [
{
"creator.role" : {"term" : "B"}
},
{
"creator.role" : {"term" : ""}
}
]
}]
}
}]
我需要检查记录中是否有至少一个'creator.role'的'term'(不为空).如果有的话,则在CSV文件中为该字段提供1,否则为0.
I need to check if there is at least one 'term' (that is not empty) for 'creator.role' in a record or not. If there is I give a 1 else a 0 for that field in a CSV-file.
由于有较早的帖子,我设法访问了字段创建者",尽管它可以是对象或数组(请参阅:
Thanks to the answers on an earlier post, I managed to access a field 'creator' although it could be an object or an array (see: Accessing field with jq that can be string or array).
但是现在对于带有特殊字符."的字段"creator.role",我也遇到了同样的问题.而且不知道该如何处理.
But now I also have the same problem for the field 'creator.role' with the special character '.' and don't know how to handle that.
我尝试的代码:
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"
在这种情况下我想要获得的输出是:
The output I want to get in this case is:
1,
0,
0,
1,
推荐答案
jq
解决方案:
jq
solution:
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
这篇关于用jq访问包含特殊字符的字段,该字段可以是对象或数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!