json - 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
解决方案
假设 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
,或者如果您想吃蛋糕并吃掉它,则可以考虑使用一些更复杂的变体。
推荐阅读
- reactjs - Sum 不是开玩笑的函数
- go - 函数之间如何处理接口类型?
- python - 如何使用sklearn找到最接近K的点的索引意味着聚类中心?
- r - 如何检查数字是否仅在一组中增加?
- java - 第一次在控制台中显示 InvocationTargetException 而不是 NoClassDefFoundError 的目的
- pine-script - 如何将 Mql4 indicatorCounted() 转换为 Pinescript
- r - 基于 r 中条件的子集数据
- discord.js - DiscordJS Commando TypeError:无法读取 null 的属性“on”
- pandas - 如何将累积频率值转换为正常频率
- python - Tkinter 图像渲染很慢。我应该如何改进它?