Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

json.Unmarshal convert map to slice

Given the following JSON string:

{
 "username":"bob",
 "name":"Robert",
 "locations": [
   {
    "city": "Paris",
    "country": "France"
   },
   {
    "city": "Los Angeles",
    "country": "US"
   }
 ]
}

I need a way to unmarshal this into the a struct like this:

type User struct {
 Username string
 Name string
 Cities []string
}

Where Cities is a slice containing the "city" values, and "country" is discarded.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I think this can be done using a custom JSON.Unmarshal function, but not sure how to do that.

>Solution :

You can define new type for Cities and implement custom Unmarshaler:

type User struct {
    Username string   `json:"username"`
    Name     string   `json:"name"`
    Cities   []Cities `json:"locations"`
}

type Cities string

func (c *Cities) UnmarshalJSON(data []byte) error {
    tmp := struct {
        City string `json:"city"`
    }{}
    err := json.Unmarshal(data, &tmp)
    if err != nil {
        return err
    }
    *c = Cities(tmp.City)
    return nil
}

PLAYGROUND

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading