Home > OS >  How to map two keys to a single member in JSON struct. (with Marshal/Unmarshal)
How to map two keys to a single member in JSON struct. (with Marshal/Unmarshal)

Time:02-11

I have a situation where my API return []byte {"name":"Windows"} on Windows and {"myName":"Linux"} on Linux, both are reporting OS Name but the key (name/MyName) is changed based on OS. How to Marshal/Unmarshal it to a JSON struct. Where I have single ember that can hold OS Name.

type OsName struct {    
    Name   string `json:"name"` //I want to map Myname as well to this member.
}

Note: above question is not about how to get OS name, its about how to map 2 different keys to a single Json member.

CodePudding user response:

Probably not the best solution, but you can write an adapter that typecasts the struct in base to the OS:

type OsName struct {
    Name string `json:"name"`
}

type LinuxOsName struct {
    Name string `json:"myName"`
}

func adapt(o OsName) interface{} {
    if o.Name == "Linux" {
        l := LinuxOsName(o)
        return &l
    }
    return &o
}

func print(o OsName) {
    b, err := json.Marshal(adapt(o))
    if err != nil {
        fmt.Printf("Error: %s\n", err)
    }
    fmt.Println(string(b))
}

https://go.dev/play/p/_M1orrGIP9p.go

CodePudding user response:

You should probably Unmarshall to a map[string]string{} and then go from there.

    dataFromAPI := "{\"name\": \"Windows\"}"
    m := map[string]string{}
    err := json.Unmarshal([]byte(dataFromAPI), &m)
    if err != nil {
        panic(err)
    }
    if _, ok := m["name"]; ok {
        fmt.Println(m["name"]) // or m["myName"]
    }
  • Related