I have a JSON code in the following format, and I'm having trouble figuring out how to use JQ to call information from the nested dictionaries within the objects within the list - if that makes sense. The list is the entire Value of the highest dictionary. Here is a sample of the structure:
{ "product" : [ { "A_key1" : "valueA1",
"A_key2" : "valueA2",
"A_key3" : {"keyA3x_nested" : "valueA3x_nested", "keyA3y_nested" : "valueA3y_nested"}
},
{ "B_key1" : "valueB1",
"B_key2" : "valueB2",
"B_key3" : {"keyB3x_nested" : "valueB3x_nested", "keyB3y_nested" : "valueB3y_nested"}
},
]
}
What I'm trying to do is select only some items from different positions within the hierarchy as follows:
{ "product": { "A_key1": "valueA1", "A_key3": {"keyA3y_nested": "valueA3y_nested"} "B_key1": "valueB1", "B_key3": {"keyB3y_nested": "valueB3y_nested"} } }
So far, I am able to do this on the command prompt: curl https://sample_api | jq '{product : .product[0]}'
^ That returns the entire object for "A" which includes all 3 of A's keys, but how do I just pull information selectively from lower in the hierarchy?
Thank you.
CodePudding user response:
this code should work for you:
curl https://sample_api | \
jq -r '(.product[0] | .A_key1, .A_key3.keyA3y_nested),
(.product[1] | .B_key1, .B_key3.keyB3y_nested)'
CodePudding user response:
Hope this achieves what you are expecting :
#!/bin/bash
jq '. as $root | null '"$(jq -nr '
def spread_paths($array):
reduce $array[] as $element ([];
. (if ($element|type) == "object"
then ($element | to_entries | map(.key spread_paths(.value)[]) )
else [$element] end)
);
spread_paths([
{".product[0].": ["A_key1", "A_key3.keyA3y_nested"]},
{".product[1].": ["B_key1", "B_key3.keyB3y_nested"]}
])[] | "|\(.)=$root\(.)"
') | map_values(.|add)" input-file