I have a JSON data like this:
[
{
"tone_id": "anger",
"score": 0.012,
"tone_name": "Anger"
},
{
"tone_id": "disgust",
"score": 0.002,
"tone_name": "Disgust"
},
{
"tone_id": "fear",
"score": 0.14,
"tone_name": "Fear"
},
{
"tone_id": "joy",
"score": 0.42,
"tone_name": "Joy"
}
]
I want to convert it into something like the following using jq
:
{
"anger": 0.012,
"disgust": 0.002,
"fear": 0.14,
"joy": 0.42
}
Best I could do is:
cat result.json | jq '.[] | { (.tone_id): .score }'
which gave the following:
{
"anger": 0.012
}
{
"disgust": 0.002
}
{
"fear": 0.14
}
{
"joy": 0.42
}
I know I can easily do this using other methods. Just wanted to know if it's possible using
jq
one-liner?
A single-invocation one-liner:
jq 'map( {(.tone_id): .score} ) | add'
(You could also wrap square brackets around .[] | { (.tone_id): .score }
before passing to add
— the two approaches are equivalent.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With