Accessing field with jq that contains a special character and can be an object or an array [duplicate]

北城以北 提交于 2019-12-11 04:14:10

问题


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,

回答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


来源:https://stackoverflow.com/questions/49427529/accessing-field-with-jq-that-contains-a-special-character-and-can-be-an-object-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!