2

For following JSON

{
    "Jon": {
       "Age": 15
    },
    "Mary": {
       "Age": 17
    } 
}

how can i map it into golang struct, normally, the structure will be

type Person struct {
    Name string `json:??,string`
    Age int `json:Age, int`
}

as the json field name is the attribute of struct, thank you in advance.

1

1 Answer 1

4

You have to use custom JSON marshalling

package main

    import (
        "encoding/json"
        "log"
        "fmt"
    )

    type Person struct {
        Name string `json:??,string`
        Age  int    `json:Age, int`
    }

    type People map[string]*Person

    func (p *People) UnmarshalJSON(data []byte) error {
        var transient = make(map[string]*Person)
        err := json.Unmarshal(data, &transient)
        if err != nil {
            return err
        }
        for k, v := range transient {
            v.Name = k
            (*p)[k] = v
        }
        return nil
    }

    func main() {

        jsonInput := `
        {
            "Jon": {
        "Age": 15
        },
            "Mary": {
        "Age": 17
        }
        }
    `

        var people People = make(map[string]*Person)

        err := people.UnmarshalJSON([]byte(jsonInput))
        if err != nil {
            log.Fatal(err)
        }

        for _, person := range people {
            fmt.Printf("%v -> %v\n", person.Name, person.Age)
        }
    }

Sign up to request clarification or add additional context in comments.

1 Comment

why you have used pointer receiver in the UnmarshalJSON function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.