使用包含特殊字符且可以是对象或数组的 jq 访问字段
Accessing field with jq that contains a special character and can be an object or an array
我在 file.json 中有大量数据转储,如下所示:
[{
"recordList" : {
"record" : [{
"Production" : {
"creator.role" : {
"term" : "A"
}
}
},
{
"Production" : {}
},
{
"Production" : {
"creator.role" : {
"term" : ""
}
}
},
{
"Production" : [
{
"creator.role" : {"term" : "B"}
},
{
"creator.role" : {"term" : ""}
}
]
}]
}
}]
我需要检查一条记录中是否至少有一个'term'(不为空)'creator.role'。如果有,我在 CSV 文件中为该字段提供 1,否则为 0。
多亏了之前 post 的回答,我设法访问了一个字段 'creator' 尽管它可能是一个对象或数组(参见:)。
但现在我也遇到了同样的问题 '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
我在 file.json 中有大量数据转储,如下所示:
[{
"recordList" : {
"record" : [{
"Production" : {
"creator.role" : {
"term" : "A"
}
}
},
{
"Production" : {}
},
{
"Production" : {
"creator.role" : {
"term" : ""
}
}
},
{
"Production" : [
{
"creator.role" : {"term" : "B"}
},
{
"creator.role" : {"term" : ""}
}
]
}]
}
}]
我需要检查一条记录中是否至少有一个'term'(不为空)'creator.role'。如果有,我在 CSV 文件中为该字段提供 1,否则为 0。
多亏了之前 post 的回答,我设法访问了一个字段 'creator' 尽管它可能是一个对象或数组(参见:
但现在我也遇到了同样的问题 '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