10

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?

3
  • show, how the potential 3rd and 4th objects should be processed? Extend your input array Commented Nov 29, 2017 at 11:19
  • It's just a list of tone_id and their respective scores... I want as many keys in my final object as the number of elements in the original list. Commented Nov 29, 2017 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. Commented Nov 29, 2017 at 11:30

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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 } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.