There is such code:

package main import ( "net/http" _ "github.com/go-sql-driver/mysql" "database/sql" "fmt" "encoding/json" "io" ) type User struct { id int name string email string } func index(response http.ResponseWriter, request *http.Request) { response.Header().Set("Content-type", "json") users := getAll() responseData := map[string][]*User{ "data": users, } jsonResponse, _ := json.Marshal(responseData) io.WriteString(response, string(jsonResponse)) } func getAll() []*User { db, err := sql.Open("mysql", "root:@/testexample") if err != nil { fmt.Println(err) } rows, err := db.Query("select id, `name`, email from users") if err != nil { fmt.Println(err) } defer rows.Close() users := make([]*User, 0) for rows.Next() { user := new(User) err := rows.Scan(&user.id, &user.name, &user.email) if err != nil { fmt.Println(err) } users = append(users, user) } if err = rows.Err(); err != nil { fmt.Println(err) } return users } func main() { http.HandleFunc("/", index) http.ListenAndServe(":9000", nil) } 

But the output is {"data":[{}]} , although if you do, for example, like this fmt.Println(users[0].name) , then the name is printed, so the array is not empty. If you do this:

 jsonResponse, _ := json.Marshal(users) fmt.Println(jsonResponse) 

then [91 123 125 93] 91,123,125 [91 123 125 93] come out - where does it come from?

Your question has been flagged as a possible duplicate of another question. If the answer does not solve your problem, please edit your question and mark the differences.

As we can see, the question is “Array of structures in json”, and not “json into an array of structures”, so no, this is not a duplicate.

    1 answer 1

    First, the encoding/json packet, like any such packet, only works with exported structure fields. So that

     type User struct { ID int Name string Email string } 

    Secondly,

    ... will be derived [91 123 125 93], where does it come from?

    These are the bytes into which you serialized the structures. If you want to print bytes as a string, use

     fmt.Printf("%s", b)