8

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?

peak
  • 105,803
  • 17
  • 152
  • 177
munikarmanish
  • 352
  • 2
  • 3
  • 13
  • show, how the potential 3rd and 4th objects should be processed? Extend your input array – RomanPerekhrest Nov 29 '17 at 11:19
  • It's just a list of `tone_id` and their respective `score`s... I want as many keys in my final object as the number of elements in the original list. – munikarmanish Nov 29 '17 at 11:21
  • @RomanPerekhrest Exactly how the 1st and 2nd objects are processed. Extract `tone_id` and `score` and make them key, value respectively in the final output. I've added more concrete example above. – munikarmanish Nov 29 '17 at 11:30

3 Answers3

9

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

peak
  • 105,803
  • 17
  • 152
  • 177
1

You can use from_entries:

jq '[.[] | {key: .tone_id, value: .score}] | from_entries' tmp.json
# or jq 'map({key: .tone_id, value: .score}) | from_entries' tmp.json

although in this case I don't see anything to recommend it over @peak's add solution.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

With reduce function:

jq 'reduce .[] as $o ({}; .[$o["tone_id"]] = $o["score"])' result.json

The output:

{
  "anger": 0.012,
  "disgust": 0.002,
  "fear": 0.14,
  "joy": 0.42
}
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105