json - 从json数据制作表格时出现jq "object cannot be tsv-formatted, only array"错误

标签 json bash csv export-to-csv jq

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

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

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 结合使用来尝试构建和填充表格,但遇到了此错误:

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

我的目标是在表中只有一个列标题行,而不是每个条目一个,当然还要显示数据而不是错误。 '(.[], 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*"-")) 中包含了 .[]——第一部分是毫无意义,除了将您的 map 内容(在 TSV 内容中无效,不是列表)插入数据流之外什么都不做。

关于json - 从json数据制作表格时出现jq "object cannot be tsv-formatted, only array"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59973594/

相关文章:

javascript - 如何在 PHP 中对 HTML 进行 JSON 编码?

c - 平均执行时间

bash - 从 Applescript 中运行 bash 脚本

csv - LibreOffice Calc : How to open CSV with numbers as text?

mysql - 如何通过 PhpMyAdmin 在 mysql 数据库中插入希腊文本

javascript - JSON 编码的多维数组返回错误的语法(意外的])

javascript - 在 camunda 进程中的进程变量中传递 json

javascript - 加载路由 : TypeError: Cannot set property 'typeKey' of undefined 时出现 Ember Data 1.0 错误

linux - unix - 文件中每列的最大(长度)

java - 将 .csv 转换为数组列表