代码之家  ›  专栏  ›  技术社区  ›  Tine

使用jq访问字段,jq可以是字符串或数组

jq
  •  2
  • Tine  · 技术社区  · 7 年前

    我在json中有一个大数据转储,如下所示:

    [{
       "recordList" : {
          "record" : [{
              "Production" : {
                  "creator" : {
                      "name" : "A"
                  }
              }
          },
          {
              "Production" : {}
          },
          {
              "Production" : [{
                  "creator" : {
                      "name" : "B"
                  },
                  "creator" : {
                      "name" : "C"
                  }
                  }]
              }]
          }
    }]
    

    我需要检查记录中是否至少有一个创建者。如果有,我给CSV文件中的该字段加1或0。

    我的代码:

    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
    

    问题是,当有多个创建者时,“生产”字段只是一个数组。

    在这种情况下,我想得到的结果是:

    1,
    0,
    1,
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   RomanPerekhrest    7 年前

    jq 解决方案:

    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,
    
        2
  •  0
  •   peak    7 年前

    简化的jq解决方案:

    jq -r '.[].recordList.record[].Production 
       | ((type == "array" and .[0].creator.name) or .creator.name) 
       | if . then "1," else "0," end' file.json