How to reformat specific data from json with jq

169 Views Asked by At

I'm new to json and want to extract data (blocks) from a specific json. I've tried to find information on how to do this with jq but so far I cannot seem to get what I want.

My json:

{
   "now" : 1589987097.9,
   "aircraft" : [
      {
         "mlat" : [],
         "rssi" : -26.2,
         "track" : 319,
         "speed" : 354,
         "messages" : 16,
         "seen" : 0.7,
         "altitude" : 38000,
         "vert_rate" : 0,
         "hex" : "44b5b4",
         "tisb" : []
      },
      {
         "squawk" : "6220",
         "altitude" : 675,
         "seen" : 1.1,
         "messages" : 7220,
         "tisb" : [],
         "hex" : "484a95",
         "mlat" : [],
         "rssi" : -22
      },
      {
         "hex" : "484846",
         "tisb" : [],
         "messages" : 20,
         "speed" : 89,
         "seen" : 0.4,
         "squawk" : "7000",
         "altitude" : 500,
         "rssi" : -23.7,
         "track" : 185,
         "mlat" : []
      },
      {
         "category" : "B1",
         "mlat" : [],
         "rssi" : -24.3,
         "flight" : "ZSGBX   ",
         "altitude" : 3050,
         "squawk" : "7000",
         "seen" : 16.8,
         "messages" : 37,
         "tisb" : [],
         "hex" : "00901a"
      }
 ],
   "messages" : 35857757
} 

I would like to reformat this json to only include 'blocks' that contain specific hex values.

So for example, I want I would like my output to contain 44b5b4 and 00901a:


{
   "now" : 1589987097.9,
   "aircraft" : [
      {
         "mlat" : [],
         "rssi" : -26.2,
         "track" : 319,
         "speed" : 354,
         "messages" : 16,
         "seen" : 0.7,
         "altitude" : 38000,
         "vert_rate" : 0,
         "hex" : "44b5b4",
         "tisb" : []
      },
      {
         "category" : "B1",
         "mlat" : [],
         "rssi" : -24.3,
         "flight" : "ZSGBX   ",
         "altitude" : 3050,
         "squawk" : "7000",
         "seen" : 16.8,
         "messages" : 37,
         "tisb" : [],
         "hex" : "00901a"
      }
 ],
   "messages" : 35857757
}

Can someone tell me how to remove all items not having those 2 hex identifiers but still keep the same json structure?

Thanks a lot!

2

There are 2 best solutions below

0
oguz ismail On

Select blocks whose hex matches one of the specific values and update aircraft to leave only those.

.aircraft |= map(select(.hex | IN("44b5b4", "00901a")))

Online demo

0
Inian On

Do a select() on the array aircraft, matching only the required hex values. The map() function takes input the entire array and the result of the select operation i.e. filtering of objects based on the .hex value is updated back |= to the original array and the rest of the fields are kept intact.

jq '.aircraft |= map(select(.hex == "44b5b4" or .hex == "00901a"))' json