Home > Blockchain >  using JQ to extract information from json file
using JQ to extract information from json file

Time:09-30

I currently have a JSON file that is around 15K of lines of code. I wish to extract some info and can do it individually using the commands bellow into 4 separate CSV files. I can't figure out if I can reduce this into a single command so that all the data goes neatly into a CSV.

This is what I have so far.

jq -r '.ServiceEngine[]?.data_vnics[]?.vlan_interfaces[]?.vnic_networks[].ip.ip_addr.addr' config_AviCluster.json > config_AviCluster.IP_address.csv
jq -r '.ServiceEngine[]?.data_vnics[]?.vlan_interfaces[].if_name' config_AviCluster.json > config_AviCluster.Interface_Name.csv
jq -r '.ServiceEngine[]?.data_vnics[]?.vlan_interfaces[]?.vnic_networks[].ip.mask' config_AviCluster.json > config_AviCluster.IP_Mask.csv
jq -r '.ServiceEngine[]?.data_vnics[]?.vlan_interfaces[].vlan_id' config_AviCluster.json > config_AviCluster.vlan_ID.csv

That is 4 separate commands and then I manually merge the CSV into a single file. Could this be improved? If so any advice and guidance would be great.

Kinds regards

CodePudding user response:

In theory, the following should create a new JSON structure with new information. But need a sample dataset to accurately test it.

jq -r '.ServiceEngine[]?.data_vnics[]?.vlan_interfaces[]|{ip_addr: .vnic_networks[].ip.ip_addr.addr, netmask: .vnic_networks[].ip.mask, iface: .if_name, vlan: .vlan_id}' config_AviCluster.json

Output

{
    "ip_addr": "0.0.0.0",
    "netmask": "255.255.255.0",
    "iface": "eth0",
    "vlan_id": "1"
}
  • Related