skip to Main Content

My json input is:

{
"zoo": [
   { "room": { "name": "x" }, "gpu": { "id": "fish",  "sum": 0 } },
   { "room": { "name": "y" }, "gpu": { "id": "zebra", "sum": 797 } }
  ]
}

I need to copy from zebra’s sum into fish’s sum. So, the output will be looked like:

{
"zoo": [
   { "room": { "name": "x" }, "gpu": { "id": "fish",  "sum": 797 } },
   { "room": { "name": "y" }, "gpu": { "id": "zebra", "sum": 797 } }
  ]
}

But, I could not know the order of the table, so, I could not use the tables index. Actually, I need to do it be the field "name".

2

Answers


  1. Again, iterate over all items using .[], and use select to filter for the right ones:

    (.zoo[].gpu | select(.id == "fish").sum) =
    (.zoo[].gpu | select(.id == "zebra").sum)
    

    Demo

    Actually, I need to do it be the field "name".

    (.zoo[] | select(.room.name == "x").gpu.sum) =
    (.zoo[] | select(.room.name == "y").gpu.sum)
    

    Demo

    Login or Signup to reply.
  2. A pedestrian but fairly robust solution would be:

    (.zoo|first(.[]|select(.room.name=="y").gpu.sum)//null) as $sum
    | if $sum
      then .zoo |= map(if .room.name=="x" then .gpu.sum=$sum else . end)
      else .
      end
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search