首页 > 解决方案 > JQ 将特定键的 JSON 转换为 CSV

问题描述

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

文件.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

标签: jsonbashcsvjq

解决方案


假设 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,或者如果您想吃蛋糕并吃掉它,则可以考虑使用一些更复杂的变体。


推荐阅读