Golang changing value in json.RawMessage

Issue

I have json.RawMessage and for getting I need to send a request to API. My problem is that I need to make a change in that message I just need to change one field, so my question is what is the most effective way to do it

json.RawMessage
{
        "make": "VW",
        "model": "ARTEON",
        "version": "2.0 TDI",
        "year_min": 2017,
        "power_ps": 200,
        "fuel": "diesel",
        "body_type": "sedan",
        "currency": "EUR",
        "co2_emission": 130
    }

so for example I want to change fuel type from diesel to gasoline

expected output
{
        "make": "VW",
        "model": "ARTEON",
        "version": "2.0 TDI",
        "year_min": 2017,
        "power_ps": 200,
        "fuel": "gasoline",
        "body_type": "sedan",
        "currency": "EUR",
        "co2_emission": 130
    }

Solution

In addition to the comment from @mkopriva(That I think is the more preferable way), you can try using a map instead of a struct(If a struct is not applicable to you).

package main

import (
    "encoding/json"
    "fmt"
)

var rm = json.RawMessage(`{
        "make": "VW",
        "model": "ARTEON",
        "version": "2.0 TDI",
        "year_min": 2017,
        "power_ps": 200,
        "fuel": "diesel",
        "body_type": "sedan",
        "currency": "EUR",
        "co2_emission": 130
    }`)

func main() {
    var objmap map[string]interface{}
    
    err := json.Unmarshal(rm, &objmap)
    if err != nil {
        panic(err)
    }
    
    objmap["fuel"] = "gasoline"
    
    result, err := json.Marshal(objmap)
    if err != nil {
        panic(err)
    }
    
    fmt.Println(string(result))
}

https://go.dev/play/p/nue-SA-LGVf

Answered By – Danil Perestoronin

Answer Checked By – Gilberto Lyons (GoLangFix Admin)

Leave a Reply

Your email address will not be published.