1

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,
Tine
  • 35
  • 4
  • Note, your last `"Production" : [{}...]` item will eventually contain an object with one key, not 2. Objects can't have repeated keys, that's why it'll "collapsed". You can not have `1,` for your last `"Production"` item – RomanPerekhrest Mar 22 '18 at 13:44
  • Okey, I see. The last 'Production' should have 2 objects instead of 1. – Tine Mar 22 '18 at 14:11
  • I changed it in my question. So that part is solved, but I still don't know how to handle the special character in this case. – Tine Mar 22 '18 at 14:18

1 Answers1

0

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
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105