使JQ将对象数组转换为字符串

jag*_*ago 3 json jq

我有一个JSON文件:

{
  "ClassIdentifier": "consumer-leads",
  "StateMode": "txt-2300",
  "StateGroups": []
}
{
  "ClassIdentifier": "main",
  "StateMode": null,
  "StateGroups": [
    {
      "Status": "active",
      "StateGroupName": "default"
    },
    {
      "Status": "active",
      "StateGroupName": "brown-space"
    },
    {
      "Status": "active",
      "StateGroupName": "txt-hosts"
    }
  ]
}
{
  "ClassIdentifier": "paid-media",
  "StateMode": "txt-2300",
  "StateGroups": []
}
{
  "ClassIdentifier": "reports",
  "StateMode": null,
  "StateGroups": [
    {
      "Status": "active",
      "StateGroupName": "txt-hosts"
    },
    {
      "Status": "active",
      "StateGroupName": "grey-space"
    },
    {
      "Status": "active",
      "StateGroupName": "default"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我需要的输出:

consumer-leads,txt-2300,null
main,null,brown-space|default|txt-hosts
paid-media,txt-2300,null
reports,null,default|grey-space|txt-hosts
Run Code Online (Sandbox Code Playgroud)

请注意,StateGroups(如果它们一直存在)按StateGroupName排序为(或之前)它们被转换为由竖线分隔的值字符串.

我所尝试的已经给了我部分结果,但没有真正的工作:

cat json_file |
      jq -r '[ .ClassIdentifier,
               .StateMode,
               .StateGroups[]
             ]'

cat json_file |
      jq -r '{ ClassIdentifier,
               StateMode
             } +
             ( .StateGroups[] | { StateGroupName,  Status } )
             '

cat json_file |
      jq -r ' [ .ClassIdentifier,
              .StateMode,
              .StateGroups |= sort_by( .StateGroupName )
             ]'
Run Code Online (Sandbox Code Playgroud)

更新:我们必须使用JQ 1.3,所以请记住回复.

Jef*_*ado 7

这应该工作:

[
    .ClassIdentifier,
    .StateMode // "null",
    (.StateGroups
        | map(select(.Status=="active").StateGroupName)
        | sort
        | join("|")
        | if .=="" then "null" else . end
    )
] | @csv
Run Code Online (Sandbox Code Playgroud)

哪个产生:

"consumer-leads","txt-2300","null"
"main","null","brown-space|default|txt-hosts"
"paid-media","txt-2300","null"
"reports","null","default|grey-space|txt-hosts"
Run Code Online (Sandbox Code Playgroud)

请注意,由于您使用的是1.3,join/1因此无法使用.但要实现自己并不困难.

def join(sep): sep as $sep
    | reduce .[1:][] as $item (.[0]|tostring; . + $sep + $item)
    ;
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢您定义连接方法. (3认同)