D
D
Daniel Literate2016-12-06 22:12:36
go
Daniel Literate, 2016-12-06 22:12:36

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"}}

The bottom line is that the name, id and method fields should always be there, but params changes from the method and so on.
And it turns out the question is how to parse it correctly in Go?
1st option. Head-on.
Create two structures with required parameters and a structure with all possible parameters and decode:
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)

In principle, it works, but the missing fields are replaced by default values ​​and eat up memory.
Somehow not very pretty.
2nd option. With interface. I don't know how to complete it.
Make structure for required fields and interface for params.
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)

Everything turns out with default values, but the interface turns into a map
//Вывод структуры после декодирования
Player 2 game map[action:move player:Vasya]

but I would like to somehow assemble it later into a struct, how to decode it again into the desired structure.
The question is how to implement this to the end?
Those. or turn this interface into a struct or map that has already turned out to be turned into a struct.
Or maybe there are other solutions.
Also as an option.
Is it possible to somehow throw params into a separate json string? And then parse it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
om1058, 2016-12-07
@Fuckoff95

You can parse in parts. Standard example from documentation: https://golang.org/pkg/encoding/json/#example_RawM...

E
Evgeniy Ivakha, 2016-12-08
@ivahaev

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 question

Ask a Question

731 491 924 answers to any question