JSON:
"{
"a": "https://is2-ssl.com/",
"b": "https://a5.-ssl.com/",
"type": "response",
"c": [
{
"Number": 1,
"Reportname": "XXX",
"size": "2.5",
"Variants": [
"YYY"
]
}
],
"Meta": "ABC"
}
Required Output:
XXX,a,https://is2-ssl.com/
XXX,b,https://a5.-ssl.com/
I want to print those key value pairs in which the value contains "http"(url) and merge the key and value with delimiter "," and add ReportName to them
Best Answer
Assuming the initial
"
in the JSON document is a typo, that you want the.ReportName
key's value from the first entry in thec
array, and that you want the output as CSV:The
jq
expression:This first picks out the
.Reportname
value and assigns it to the internaljq
variable$n
. It then rewrites the original object by discarding any key not associated with a string starting with the substringhttp
.The example document is, after
map_values()
reduced toThis is then converted with
to_entries
into the equivalent of... to get access to the keys themselves.
This array is expanded into a set of objects with
[]
and the saved value in$n
together with the.key
and.value
part of each object in the set is used to create an array that is converted by@csv
to quoted CSV output.Another
jq
expression with the same output, but that doesto_entries
a bit earlier and then doesmap()
on the created array rather than on the values of an object as we do withmap_values()
above.