用jq访问字段,该字段可以是字符串或数组 [英] Accessing field with jq that can be string or array
本文介绍了用jq访问字段,该字段可以是字符串或数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在json中有大量数据转储,如下所示:
I have a large dump of data in json that looks like:
[{
"recordList" : {
"record" : [{
"Production" : {
"creator" : {
"name" : "A"
}
}
},
{
"Production" : {}
},
{
"Production" : [{
"creator" : {
"name" : "B"
},
"creator" : {
"name" : "C"
}
}]
}]
}
}]
我需要检查记录中是否至少有一个创建者.如果有的话,则在CSV文件中为该字段提供1,否则为0.
I need to check if there is at least one creator in a record or not. If there is I give a 1 else a 0 for that field in a CSV-file.
我的代码:
jq -r '.[].recordList.record[]|"\(if ((.Production.creator.name)? // (.Production[]?.creator.name)?) == null or ((.Production.creator.name)?|length // (.Production[]?.creator.name)?|length) == 0 then 0 else 1 end),"' file.json
问题在于,当有多个创建者时,生产"字段只是一个数组.
The problem is that the field 'Production' is only an array when there are multiple creators.
在这种情况下,我想要得到的结果是:
The result I want to get in this case is:
1,
0,
1,
推荐答案
jq
解决方案:
jq
solution:
jq -r '.[].recordList.record[].Production
| "\(if ((type == "array" and .[0].creator.name !="")
or (type == "object" and .creator.name and .creator.name !=""))
then 1 else 0 end),"' file.json
输出:
1,
0,
1,
这篇关于用jq访问字段,该字段可以是字符串或数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文