Home > database >  Is there an efficient way in jq_filter for parsing and filtering key, values
Is there an efficient way in jq_filter for parsing and filtering key, values

Time:03-25

I have json like below:

{
  "serge12": {
    "17": {
      "wlan_id": "23",
      "interface": "nwce",
      "bssid": "00:b7:71:a5:de:60",
      "atf_override": "n/a",
      "atf_policy_id": "n/a",
      "atf_policy_name": "n/a",
      "ssid": "test",
      "wlan_profile_name": "wlan",
      "location": "default location"
    },
    "18": {
      "wlan_id": "24",
      "interface": "nwcg",
      "bssid": "00:b7:71:a5:de:61",
      "atf_override": "n/a",
      "atf_policy_id": "n/a",
      "atf_policy_name": "n/a",
      "ssid": "tetra",
      "wlan_profile_name": "wnet",
      "location": "default location"
    },
    "serge13": {
      "27": {
        "wlan_id": "23",
        "interface": "nwce",
        "bssid": "00:b7:71:a5:de:58",
        "atf_override": "n/a",
        "atf_policy_id": "n/a",
        "atf_policy_name": "n/a",
        "ssid": "test",
        "wlan_profile_name": "wlan",
        "location": "default location"
      },
      "29": {
        "wlan_id": "24",
        "interface": "nwcg",
        "bssid": "00:b7:71:a5:de:69",
        "atf_override": "n/a",
        "atf_policy_id": "n/a",
        "atf_policy_name": "n/a",
        "ssid": "tetra_glance",
        "wlan_profile_name": "wnet",
        "location": "default location"
      }
    }
  }
}

This is a sample json file and will be big in actual output. From this json output,I need to filter "ssid","bssid","wlan_profile_name","location" and expected output is like below .

I am using python3.9 with jq

[
  {
    "ap_name": "serge12",
    "bssid": "00:b7:71:a5:de:60",
    "location": "default location",
    "ssid": "test",
    "wlan_profile_name": "wnet"
  },
  {
    "ap_name": "serge12",
    "bssid": "00:b7:71:a5:de:61",
    "ssid": "tetraglance",
    "wlan_profile_name": "wnet",
    "location": "default location"
  },
  {
    "ap_name": "serge13",
    "bssid": "00:b7:71:a5:de:58",
    "location": "default location",
    "ssid": "test",
    "wlan_profile_name": "wnet"
  },
  {
    "ap_name": "serge13",
    "bssid": "00:b7:71:a5:de:69",
    "ssid": "tetraglance",
    "wlan_profile_name": "wlan",
    "location": "default location"
  }
]

I was trying to use jq_filter but not able to parse them in one shot

jq_filter1 = . | to_entries | map({device:.key})
jq_filter2 = .[] | .| ( to_entries | map({ssid:.value.ssid, bssid:.value.bssid,location:.value.location}))

I dont know if we can join them or some efficient way to handle this.

CodePudding user response:

[
   path( .. | objects | select( .ssid ) ) as $path |
   getpath($path) |
   { app_name: $path[-2], ssid, bssid, wlan_profile_name, location }
]

Demo on jqplay

  • Related