Answer the question
In order to leave comments, you need to log in
What approach to parsing JSON to choose in Golang?
There is data in JSON, for example two options:
{"name": "Player", "id": 1, "method": "server", "params": {"login": "Vasya", "pass": "****"}}
{"name": "Player", "id": 2, "method": "game", "params":{"action":"move","player":"Vasya"}}
type Message struct {
Name string `json:"name"`
Id int `json:"id"`
Method string `json:"method"`
Params Params `json:"params"`
}
type Params struct {
Action string `json:"action"`
Player string `json:"player"`
Login string `json:"login"`
Pass string `json:"pass"`
}
d := json.NewDecoder(conn) //Тут коннект от TCP
var msg Message
err := d.Decode(&msg)
type Message struct {
Name string `json:"name"`
Id int `json:"id"`
Method string `json:"method"`
Params interface{} `json:"params"`
}
d := json.NewDecoder(conn) //Тут коннект от TCP
var msg Message
err := d.Decode(&msg)
//Вывод структуры после декодирования
Player 2 game map[action:move player:Vasya]
Answer the question
In order to leave comments, you need to log in
You can parse in parts. Standard example from documentation: https://golang.org/pkg/encoding/json/#example_RawM...
There is another cool option - parse json like this:
https://github.com/buger/jsonparser
or like this
https://github.com/tidwall/gjson
More writing, but faster and more economical.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question