'Using jq to get json values

Input json:

{
"food_group": "fruit",
"glycemic_index": "low",
    "fruits": {
        "fruit_name": "apple",
        "size": "large",
        "color": "red"
    }
}

Below two jq commands work:

# jq -r 'keys_unsorted[] as $key | "\($key), \(.[$key])"' food.json
food_group, fruit
glycemic_index, low
fruits, {"fruit_name":"apple","size":"large","color":"red"}

# jq -r 'keys_unsorted[0:2] as $key | "\($key)"' food.json
["food_group","glycemic_index"]

How to get values for the first two keys using jq in the same manner? I tried below

# jq -r 'keys_unsorted[0:2] as $key | "\($key), \(.[$key])"' food.json
jq: error (at food.json:9): Cannot index object with array

Expected output:

food_group, fruit
glycemic_index, low


Solution 1:[1]

To iterate over a hash array , you can use to_entries and that will transform to a array .

After you can use select to filter rows you want to keep .

 jq -r 'to_entries[]| select(  ( .value | type ) == "string" ) | "\(.key), \(.value)" ' 

Solution 2:[2]

You can use to_entries

to_entries[] | select(.key=="food_group" or .key=="glycemic_index") | "\(.key), \(.value)"

Demo

https://jqplay.org/s/Aqvos4w7bo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 EchoMike444
Solution 2 Logan Lee