starkk92
starkk92

Reputation: 5924

extracting json using jq

I have sample Json file like this.How to extract data from it?

I have tried few things.But could not get the desired result

{
   "adults":{
               "car":{"length":[20,25],"width":[225,40]},
               "tractor":{"length":[20,23],"width":[223,40]}
            },
   "children":{
                "cycle":{"length":[20,21],"width":[221,40]},
              }
}

I want to insert this data to the database with the following columns:

age_group | vehicle | measurements

So that my final table would be

age_group | vehicle  | measurements
------------------------------------
adults      car         {"length":[20,25],"width":[225,40]}
adults      tractor     {"length":[20,21],"width":[223,40]}
children    cycle       {"length":[20,21],"width":[221,40]}

How Can I extract the info from the json object to a text file as required using jq?

Edit:how to get the inner keys as required below?

age_group | vehicle  | Dimension
    ------------------------------------
    adults      car         length
    adults      car         width

    adults      tractor     length
    adults       tractor     width
    children    cycle       length
    children    cycle        width

Upvotes: 0

Views: 406

Answers (1)

nobody0day
nobody0day

Reputation: 202

jq 'to_entries | map(.key as $mykey | .value | to_entries | map([$mykey, .key, .value])) | add ' test.json

  1. transform JSON object to standard form jq
  2. remember key we has parsed
  3. parse value JSON object
  4. construct output

update: jq 'to_entries | map(.key as $mykey | .value | to_entries | map(.key as $mykey2 | .value | to_entries | map([$mykey, $mykey2, .key]))) | add | add ' test.json

jq offers two kinds of tools that we can manipulate json files. Firstly we can filter data in json file but the filtering may lose data. Secondly we can map and reduce the data.

So we firstly must turn your variable json into fixed structure which we can access its key and value pair. After that we use filter to extract data from value field. As you have given a json file that nested 3 variable dict so we have to do three times to transform variable json to fixed filed one.

Upvotes: 1

Related Questions