jq "object cannot be tsv-formatted, only array" 从 json 数据生成 table 时出错

jq "object cannot be tsv-formatted, only array" error when making table from json data

我的脚本创建了一个 json 数据集,然后尝试将其呈现为 table。

在第一行代码的输出中,您可以看到一个示例数据集:

echo ${conn_list[@]} | jq '.'

{
  "host": {
    "name": "mike1",
    "node": "c04",
    "s_ip": "10.244.7.235",
    "s_port": "38558",
    "d_ip": "129.12.34.567",
    "d_port": "22",
    "pif_ip": "129.23.45.678",
    "pif_port": "11019"
  }
}
{
  "host": {
    "name": "fhlb-test",
    "node": "c04",
    "s_ip": "10.244.7.20",
    "s_port": "49846",
    "d_ip": "129.98.76.543",
    "d_port": "22",
    "pif_ip": "129.87.65.432",
    "pif_port": "23698"
  }
}

我将以下 jq 命令与 @tsv 一起使用来尝试构建并填充 table 但 运行 到此错误中:

echo ${conn_list[@]} | jq -r '["NAME","NODE","SOURCE IP","SOURCE PORT","DESTINATION IP","DESTINATION PORT","GATEWAY IP","GATEWAY PORT"], (.[], map(length*"-")), (.[] | [.name, .node, .s_ip, .s_port, .d_ip, .d_port, .pif_ip, .pif_port]) | @tsv'

NAME    NODE    SOURCE IP       SOURCE PORT     DESTINATION IP  DESTINATION PORT        GATEWAY IP      GATEWAY PORT
jq: error (at <stdin>:1): object ({"name":"mi...) cannot be tsv-formatted, only array
NAME    NODE    SOURCE IP       SOURCE PORT     DESTINATION IP  DESTINATION PORT        GATEWAY IP      GATEWAY PORT
jq: error (at <stdin>:1): object ({"name":"fh...) cannot be tsv-formatted, only array

我的目标是在 table 中只有一个列标题行,而不是每个条目一个,当然还要显示数据而不是错误。 '(.[], map(length*"-"))' 位用于自动生成正确大小的破折号以将列标题与数据分开。有人看到我做错了什么吗? :)

固定版本可能如下所示:

jq -rn '
# Assign the list of fields to a variable
["NAME","NODE","SOURCE IP","SOURCE PORT","DESTINATION IP","DESTINATION PORT","GATEWAY IP","GATEWAY PORT"] as $fields |
(
  $fields,                        # emit the list as a header
  ($fields | map(length*"-")),    # print separators below each header
  (inputs | .[] | [.name, .node, .s_ip, .s_port, .d_ip, .d_port, .pif_ip, .pif_port])
) | @tsv' <<<"$s" # where s is a string with your JSON content.

...作为输出发出,供您输入(无需重新格式化以对齐选项卡):

NAME    NODE    SOURCE IP   SOURCE PORT DESTINATION IP  DESTINATION PORT    GATEWAY IP  GATEWAY PORT
----    ----    ---------   ----------- --------------  ----------------    ----------  ------------
mike1   c04 10.244.7.235    38558   129.12.34.567   22  129.23.45.678   11019
fhlb-test   c04 10.244.7.20 49846   129.98.76.543   22  129.87.65.432   23698

直接的错误是 .[] 包含在 (.[], map(length*"-")) 中——第一部分毫无意义,除了插入您的地图内容(这在 TSV 内容中无效) , 不是列表) 到数据流中。