1

For this data https://jqplay.org/s/onlU9ghjn1

I can not figure out the correct syntax to do something like

.gcp_price_list | ."CP-COMPUTEENGINE-OS" | 
(
    if ( .[].cores == "shared" ) then
        .[].cores = 0.5 
    end
)

Seems I need the else part but I'm not sure what to put there. If I do:

.gcp_price_list | ."CP-COMPUTEENGINE-OS" | 
(
    if ( .[].cores == "shared" ) then
        .[].cores = 0.5 
    else .[].cores = .[].cores end
)

There is still "shared" in the result, i.e.

  "win": {
    "low": 0.02,
    "high": 0.04,
    "cores": "shared",
    "percore": true
  }

Inputs get replicated into the result, which is not what I want.

Related, but I don't find them very helpful, questions

JQ If then Else

How do I update a single value in a json document using jq?


My practical alternative is "replaced all" with a text editor, but I will leave this question here in case there is an elegant solution.

peak
  • 105,803
  • 17
  • 152
  • 177
Mzq
  • 1,796
  • 4
  • 30
  • 65

1 Answers1

0

It looks as though you want:

.gcp_price_list
| ."CP-COMPUTEENGINE-OS"
| map_values(
    if .cores == "shared" 
    then .cores = 0.5 
    else . end )

In any case, be careful when using expressions such as .[].cores as arguments of if, then, or else, because they produce a stream of results.

In future, please follow the MCVE guidelines.

Postscript

If you want to edit the JSON document, you would use |= like so:

.gcp_price_list."CP-COMPUTEENGINE-OS" |= 
  map_values(
    if ( .cores == "shared" ) then
        .cores = 0.5 
    else . end
  )
peak
  • 105,803
  • 17
  • 152
  • 177