O
O
Oleg Voitenko2018-04-22 11:26:59
go
Oleg Voitenko, 2018-04-22 11:26:59

How to properly parse data from a model?

There is a query to the table that returns data in the type:
[]*User
that is, I send usr, err := m.User(some_username) to some function,
and it returns data to me according to the []*User model
Well, I'll see what's in the console: It
fmt.Println(usr)
gives:
[0xc4201386f0]
I parse it into a string in this way:
respMySql, err := json.Marshal(usr)
through fmt.Println(string (respMySql))
I get a sane string like this:
[{"ID":4,"Username":"SomeLogin","Password":"21232f297a57a5a743894ea0e4a801fc3"} ]
Now the question is, how can I parse this string into key: value, and access its Username Password ID keys?
provide an example implementation. Unmarshal returns empty.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
danforth, 2018-04-22
@OliverV

I didn't quite understand the question. If you return []*User, then this is a slice of your users. User is a custom type based on what? If it is a structure, then it has fields. If type User is map[string]string, then this is a map. But judging by your JSON, it's still a structure.
To iterate over all users, use for range, like this:

for _, user := range users {
    fmt.Printf("%d - %s\r\n", user.ID, user.Name) // выведет пользователей в формате ID - Имя.
}

If you need to specifically refer to a specific index, then like this:
It will display the same thing, but you have addressed a specific user in the slice.
If I answered wrong, please clarify your question.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question