【问题标题】:JQ to convert JSON to CSV for specific KeysJQ 将特定键的 JSON 转换为 CSV
【发布时间】:2021-11-02 14:02:54
【问题描述】:

我正在尝试使用 jq 将所选键的 JSON 转换为 CSV。

文件.json

{
  "_ref": "ipv4address/Li5pcHY0X2FkZHJlc3yMDIuMS8w:10.202.202.1",
  "discovered_data": {
    "bgp_as": 64638,
    "device_model": "catalyst37xxStack",
    "device_port_name": "Vl2002",
    "device_port_type": "propVirtual",
    "device_type": "Switch-Router",
    "device_vendor": "Cisco",
    "discovered_name": "Test_Device.network.local",
    "discoverer": "Network Insight",
    "first_discovered": 1580161888,
    "last_discovered": 1630773758,
    "mac_address": "aa:bb:cc:dd:ee:ff",
    "mgmt_ip_address": "10.202.202.1",
    "os": "15.2(4)E10",
    "port_speed": "Unknown",
    "port_vlan_name": "TEST-DATA",
    "port_vlan_number": 2002
  },
  "ip_address": "10.202.202.1",
  "is_conflict": false,
  "mac_address": "",
  "names": ["Test_Device"],
  "network": "10.202.202.0/23",
  "network_view": "TEST VIEW",
  "objects": [],
  "status": "USED",
  "types": [
    "UNMANAGED"
  ],
  "usage": []
}

我想要的输出是:

names,ip_address,discovered_data.mac_address,discovered_data.discovered_name
Test_Device,10.202.202.1,aa:bb:cc:dd:ee:ff,Test_Device.network.local

到目前为止,我已尝试使用以下命令,但遇到一些语法错误:

jq -r 'map({names,ip_address,discovered_data.mac_address,discovered_data.discovered_name}) | (first | keys_unsorted) as $keys | map([to_entries[] | .value]) as $rows | $keys,$rows[] | @csv' < file.json

【问题讨论】:

  • 第一个细节,file.json 在第 22 行缺少",即 IP 地址。
  • 感谢您的指出。我正在更改生产数据,因此在替换 IP 地址时错过了"

标签: json bash csv jq


【解决方案1】:

假设 JSON 已修复,请考虑以下输出:

(null 
| {names,
  ip_address,
  "discovered_data.mac_address",
  "discovered_data.discovered_name"} | keys_unsorted) as $keys
| $keys, 
  ({names: .names[],
   ip_address,
   "discovered_data.mac_address": .discovered_data.mac_address,
   "discovered_data.discovered_name": .discovered_data.discovered_name }
   | [.[]])
| @csv

假设 jq 是使用 -r 命令行选项调用的,这具有生成有效 CSV 的优势。如果您希望所有的键名和值不被引用,您可能希望考虑使用join(",") 而不是@csv,或者如果您想吃蛋糕并吃掉它,可以使用一些更复杂的变体。

【讨论】:

  • 这就像一个魅力,但是,我有一个问题。来自 API 的 json 文件在 json 文件上包含方括号,当我发出命令时,它给了我jq: error (at &lt;stdin&gt;:32): Cannot index array with string "names"。有办法解决吗?
  • (.[]|{names:替换({names:
  • 效果很好:)。谢谢 ! ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 2015-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多