Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq - convert a list of objects into a summarized object

Tags:

json

arrays

jq

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?

like image 849
munikarmanish Avatar asked Nov 29 '17 11:11

munikarmanish


1 Answers

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.)

like image 58
peak Avatar answered Oct 20 '22 16:10

peak