I need to convert a JSON string using jq, as shown below, into a table format for displaying the output in the terminal.
{
"results": [
[
{
"field": "@timestamp",
"value": "2023-07-03 08:28:00.000"
},
{
"field": "CpuReserved",
"value": "8192.0"
},
{
"field": "CpuUtilized",
"value": "4056.412942708333"
},
{
"field": "MemoryReserved",
"value": "61440"
},
{
"field": "MemoryUtilized",
"value": "4311"
},
{
"field": "@ptr",
"value": "CpABClUKUTE0NjcxNzAzNzI0NzovYXdzL2Vjcy9jb250YWluZXJpbnNpZ2h0cy9pcmwtaW5mcmEtc2hhcmVkLWplbmtpbnMtbWFpbi9wZXJmb3JtYW5jZRABEjUaGAIGSaxosQAAAAAd+TFeAAZKKHIwAAABEiABKIDF9taRMTDA7v3WkTE4BkC9NEjNPFCBIRgAEAAYAQ=="
}
],
[
{
"field": "@timestamp",
"value": "2023-07-03 08:28:00.000"
},
{
"field": "CpuReserved",
"value": "8192.0"
},
{
"field": "CpuUtilized",
"value": "4056.412942708333"
},
{
"field": "MemoryReserved",
"value": "61440"
},
{
"field": "MemoryUtilized",
"value": "4311"
},
{
"field": "@ptr",
"value": "CpABClUKUTE0NjcxNzAzNzI0NzovYXdzL2Vjcy9jb250YWluZXJpbnNpZ2h0cy9pcmwtaW5mcmEtc2hhcmVkLWplbmtpbnMtbWFpbi9wZXJmb3JtYW5jZRABEjUaGAIGSaxosQAAAAAd+TFeAAZKKHIwAAABEiABKIDF9taRMTDA7v3WkTE4BkC9NEjNPFCBIRgAEAEYAQ=="
}
]
]
}
What I want to display in the terminal is as follows:
@timestamp CpuReserved CpuUtilized MemoryReserved MemoryUtilized
==========================================================================================
2023-07-03 08:16:00.000 8192.0 410.5300065104166 61440 1417
2023-07-03 08:15:00.000 8192.0 702.310791015625 61440 792
Can someone guide me in the right direction?
Best Answer
Maybe:
Without
--barred
, that looks like:You could also pipe the output of that
jq
command tovd -f json
(VisiData) instead ofmlr
(Miller) to get an interactive table viewer.Those use
jq
to extract the information andmlr
only to format the table. There is some overlap between the feature set ofjq
and that ofmlr
. For instance, you could also remove the@ptr
column withmlr
'scut
:That
jq
command, broken down and commented:The result is not JSON, but several JSONs concatenated together, but both
jq
andmlr
support that. With-c
(compact), that's NDJSON (newline-delimited JSON) where we have one JSON per line, also supported byvd
. To get proper JSON, we'd need:Where we use
map
on the.results
array so it results in another JSON array instead of iterating over the elements. So the end result is one large arrays. That's also supported byjq
(obviously as that's proper JSON),mlr
andvd
, is a bit longer to type and means those tools need to read up to the closing]
at the very end before they have anything to chew on. In practice, I've not checked whether that made any difference in terms of performance though.