Jsonify map of structs in Go

2019-06-09 16:49发布

问题:

So right now I have a struct for client connections which looks as following

type ClientConn struct {
    uuid      string
    websocket *websocket.Conn
    ip        net.Addr
    longitude float64
    latitude  float64
}

and I've also got a map of ClientConn as following

var clientList = make(map[string]*ClientConn)

so I add a new ClientConn on each connection to the clientList but what I'm trying to do is jsonify the clientList and obtain an array of ClientConn with its values and not just keys.

If I do

json.Marshal(clientList)

then I just get the keys with a empty object and what I'd like to retrieve is the whole ClientConn struct array with the values and keys.

What would be a way to do this?

回答1:

This is the daily question of the go tag.

Your struct fields has to be exported, aka start with an uppercase letter.

A good read to explain json with go is JSON and Go on the official blog.

A must-read for anyone interested in Go is Effective Go.



标签: json map struct go