nsane
nsane

Reputation: 1765

Modifying the same field in an array of objects using jq

I have an array of objects, where each object is structured as:

 {
   "impl": "pmdk",
   "pc_writes": 50,
   "threads": 1,
   "throughput (K tps)": 703014,
   "med_latency (ns)": 1334,
   "99_latency (ns)": 2358,
   "exec_time (s)": 14224471006
 }

I would like to divide the "throughput (K tps)" field in each object by 1000 and return the array in the same format. I tried using map_values in the following way:

map_values(."throughput (K tps)"/1000)

But it only returns an array of modified values as:

[703.014,...]

Instead of the entire objects, like this:

 [{
   "impl": "pmdk",
   "pc_writes": 50,
   "threads": 1,
   "throughput (K tps)": 703.014,
   "med_latency (ns)": 1334,
   "99_latency (ns)": 2358,
   "exec_time (s)": 14224471006
 },
 ...
 ]

How do I return an array of objects after dividing one of its fields by 1000?

Upvotes: 1

Views: 97

Answers (3)

0stone0
0stone0

Reputation: 43904

jq '.[] | ."throughput (K tps)" |= . / 1000'

Should edit each throughput (K tps) by dividing it by 1000.

Try it online!


Upvotes: 0

Inian
Inian

Reputation: 85550

You can use either of map or map_values for your problem. But the problem with your attempt was you were only modifying the field "throughput (K tps)" for printing into output.

Without the |= update assignment operator, only the field mentioned in the expression will be printed to console.

You can use the Update-assignment operator

map(."throughput (K tps)" |= . / 1000)

But jq gives you much more to do Arithmetic update assignments of form +=, *= and also /=, so that you can do

map(."throughput (K tps)" /= 1000)

Upvotes: 3

choroba
choroba

Reputation: 241768

Tell jq to replace the value in "throughput (K tps)" by itself divided by 1000:

jq '.[]."throughput (K tps)" |= . / 1000' file.json

Upvotes: 3

Related Questions