Home > Software design >  How can I parse array of array to struct in Go?
How can I parse array of array to struct in Go?

Time:06-12

[
[1501545600000,"a","b","c","d","pass this","e",1651363200000],[1504224000000,"a","b","c","d","pass this","e",1654041600000],
...
]

I have a bunch of arrays like that. And it came from an external API. I want to map it to a struct. And I don't need the "pass this" field. How can I do this?

And also here is my struct

type Address struct {
    RegistrationDate string `json:"registrationDate"`
    Name             string `json:"name"`
    Address          string `json:"address"`
    City             string `json:"city"`
    State            string `json:"state"`
    Zip              string `json:"zip"`
    ExpirationDate   string `json:"expirationDate"`
}

Thank you.

CodePudding user response:

You can have Address implement the json.Unmarshaler interface.

type Address struct {
    RegistrationDate int64  `json:"registrationDate"`
    Name             string `json:"name"`
    Address          string `json:"address"`
    City             string `json:"city"`
    State            string `json:"state"`
    Zip              string `json:"zip"`
    ExpirationDate   int64  `json:"expirationDate"`
}

func (a *Address) UnmarshalJSON(data []byte) error {
    var discard string
    return json.Unmarshal(data, &[]any{
        &a.RegistrationDate,
        &a.Name,
        &a.Address,
        &a.City,
        &a.State,
        &discard,
        &a.Zip,
        &a.ExpirationDate,
    })
}

https://go.dev/play/p/eSaXEQ-onOC


If you need the date fields to remain strings you can use a "converter" type to unmarshal the JSON number and then convert the resulting int to a string.

type Int64String string

func (s *Int64String) UnmarshalJSON(data []byte) error {
    var i64 int64
    if err := json.Unmarshal(data, &i64); err != nil {
        return err
    }

    *s = Int64String(strconv.FormatInt(i64, 10))
    return nil
}
type Address struct {
    RegistrationDate string `json:"registrationDate"`
    Name             string `json:"name"`
    Address          string `json:"address"`
    City             string `json:"city"`
    State            string `json:"state"`
    Zip              string `json:"zip"`
    ExpirationDate   string `json:"expirationDate"`
}

func (a *Address) UnmarshalJSON(data []byte) error {
    var discard string
    return json.Unmarshal(data, &[]any{
        (*Int64String)(&a.RegistrationDate),
        &a.Name,
        &a.Address,
        &a.City,
        &a.State,
        &discard,
        &a.Zip,
        (*Int64String)(&a.ExpirationDate),
    })
}

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

  •  Tags:  
  • go
  • Related