golang how i can get value from []interface {} type

Issue

i have var (name result["error_type"]) with type

[]interface {}

and value

[map[reason:map[phone:empty] send_at:1.636697291e+09 status:error]]

how i cat get value from type []interface {}

example result["error_type"]["128"]["reason"]["phone"]

this type i got from

var result map[string]interface{}
json.NewDecoder(r.Body).Decode(&result)

r.Body has Json

{
  "offer_name":"EbcBankruptcy",
  "offer_id":"288",
  "partner_name":"середов",
  "partner_id":"1",
  "type_system":"gb",
  "status":"success",
  "date_request":"2021-01-02 11:03",
  "bank_name":"alfa",
  "bank_id":"1",
  "type_product":"1",
  "error_type":{"128": [{"reason": {"phone": "Отсутствует обязательное поле номер телефона"}, "status": "error", "send_at": 1636697291}], "200": [{"reason": {"phone": "Отсутствует обязательное поле номер телефона"}, "status": "error", "send_at": 1636697281}]},
  "request_id":"1"
}

also i dont create structure error_type for json.NewDecoder parse because i dont know what kind id will be in error_type in json (128, 200, 300)

i try get value

test["reason"]["phone"]

but, its not work

also cast to

map[string]interface{}

its not work

Solution

As far as the understanding from the question, what I understand is you can format the data as following.

type Payload struct {
    OfferName   string                 `json:"offer_name"`
    OfferID     string                 `json:"offer_id"`
    PartnerName string                 `json:"partner_name"`
    PartnerID   string                 `json:"partner_id"`
    TypeSystem  string                 `json:"type_system"`
    Status      string                 `json:"status"`
    DateRequest string                 `json:"date_request"`
    BankName    string                 `json:"bank_name"`
    BankID      string                 `json:"bank_id"`
    TypeProduct string                 `json:"type_product"`

    // you can use the type map of array of error data here 
    ErrorType   map[string][]ErrorData `json:"error_type"`

    RequestID   string                 `json:"request_id"`
}


type ErrorData struct {
    Reason Reason `json:"reason"`
    Status string `json:"status"`
    SendAt int    `json:"send_at"`
}

type Reason struct {
    Phone string `json:"phone"`
}

With the following you can unmarshal the data to

fmt.Printf("%+v", p.ErrorType["128"][0].Reason)

In the case you are unable to know the keys of the map, you can still range over the map values and get the data.

Here is the playground link https://go.dev/play/p/oTF0JUwOj0D

Answered By – Siv

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.