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" : ""}
}
]
}]
}
}]
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).
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.
The code I tried:
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
I get this Error:
Cannot index array with string "term"
The output I want to get in this case is:
1,
0,
0,
1,
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