使用 shell 脚本将 Json 转为 Table 格式

-2 shell-script json

sfdx 差异 | 三通结果.json ;

在这里,我得到 json 格式的结果/响应,并将其添加到 result.json 文件中。下面是我得到的 json

{
  "status": 3,
  "result": {
    "source": {
      "type": "folder",
      "origin": "/source"
    },
    "target": {
      "type": "folder",
      "origin": "/target"
    },
    "difs": [
      {
        "type": "In Progress",
        "entity": "Phone",
        "result": "added"
      },
      {
        "type": "Completed",
        "entity": "SMS",
        "result": "added"
      },
      {
        "type": "Scheduled",
        "entity": "Web",
        "result": "added"
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我需要以表格格式显示它..就像 在此输入图像描述

我们有什么办法可以做到这一点。请帮忙,因为我对 shell 脚本很陌生

Kus*_*nda 5

给定当前问题中的 JSON 文档,以下jq命令会将其转换为与您显示的表格格式相对应的 CSV 形式,包括表格标题:

jq -r '["Status","Value","Result"],
    (.result.difs[] | [.type,.entity,.result]) | @csv' file.json
Run Code Online (Sandbox Code Playgroud)

首先为我们需要转换为 CSV 的每一行创建一个值数组,然后使用内置运算符@csv创建正确引用的 CSV 数据。

给定示例 JSON 文档,输出将是

"Status","Value","Result"
"In Progress","Phone","added"
"Completed","SMS","added"
"Scheduled","Web","added"
Run Code Online (Sandbox Code Playgroud)

稍后可以将其导入到您想要用来创建表格的任何电子表格程序中。

cvslook使用命令行 CSV 解析工具的工具包对此进行后处理csvkit,您可以获得该表的 Markdown 变体:

jq -r '["Status","Value","Result"],
    (.result.difs[] | [.type,.entity,.result]) | @csv' file.json |
csvlook
Run Code Online (Sandbox Code Playgroud)

这将输出

| Status      | Value | Result |
| ----------- | ----- | ------ |
| In Progress | Phone | added  |
| Completed   | SMS   | added  |
| Scheduled   | Web   | added  |
Run Code Online (Sandbox Code Playgroud)

当渲染为 markdown 时,它看起来像

地位 价值 结果
进行中 电话 添加
完全的 短信 添加
预定 网络 添加