4 ms·
It's been a while since I looked at it but back when I was trying to map a JSON wire format onto a Go structure, this was a PITA, as it typically is in strongly
by cookiecaper 10y ago
It's been a while since I looked at it but back when I was trying to map a JSON wire format onto a Go structure, this was a PITA, as it typically is in strongly-typed languages. You say it's "simple". What's the best way to go about it?
- placeybordeaux 10y agoI've found it very easy just using the Marshal and Unmarshal packages for golang: https://golang.org/pkg/encoding/json/#Unmarshal https://golang.org/pkg/encoding/json/#Unmarshal They have some reasonable examples there.
- skybrian 10y agoThe idea is that if you're inventing a new data format, you can write the Go types first, and the JSON schema is based on that. This works ok if you're starting in Go. Mapping arbitrary JSON to Go types may or may not be simple, depending on the data format.
- eberkund 10y agoThe other commenter posted a link to the official docs which explain it pretty well. I'm new to Go so I don't know what was there before but basically all I have to do is define a Go struct with the types that I want and then using struct field tags I can name the fields (for example if I want to use snakecase or something for JSON). Then when I encode to a string it automatically takes care of formatting it as JSON and I can decode a string and get back the typed struct (it will throw an error if it can't be done).