JSON in Go: Difference between revisions
Jump to navigation
Jump to search
Line 49: | Line 49: | ||
===With a <tt>Reader</tt>=== | ===With a <tt>Reader</tt>=== | ||
Using a <code>[[Go_Package_io#Reader|Reader]]</code>: | Using a <code>[[Go_Package_io#Reader|Reader]]</code>: | ||
<syntaxhighlight lang='go'> | |||
var req *http.Request = ... | |||
reader := req.Body // body implements Reader | |||
jsonDecoder = json.NewDecoder(reader) | |||
var s SomeStruct | |||
if err := jsonDecoder.decode(&s); err != nil { | |||
// ... | |||
} | |||
fmt.Printf("%+v\n", s) | |||
</syntaxhighlight> | |||
=TO PROCESS= | =TO PROCESS= | ||
<font color=darkkhaki>TO PROCESS: https://golang.cafe/blog/golang-json-marshal-example.html</font> | <font color=darkkhaki>TO PROCESS: https://golang.cafe/blog/golang-json-marshal-example.html</font> |
Revision as of 20:06, 16 October 2023
Internal
Overview
JSON Marshalling Go → JSON
JSON marshalling means generating a JSON representation from a Go object. It is done with json.Marshal()
. The result is a byte array. To convert the byte array to a string, see:
Map Marshalling
Struct Marshalling
By default, only fields that start with capital letters are marshaled. The fields that start with lower caps are invisible to the marshaling process.
type Item struct {
Color string
Size int
Options []string
}
i := Item{Color: "blue", Size: 5, Options: []string{"brake", "acceleration", "lights"}}
ba, err := json.Marshal(i) // pass the value
fmt.Println(string(ba))
JSON Unmarshalling JSON → Go
Unmarshalling into Struct
With a Byte Slice
type Item struct {
Color string
Size int
Options []string
}
s := "{\"Color\":\"blue\",\"Size\":5,\"Options\":[\"brake\",\"acceleration\",\"lights\"]}"
ba := []byte(s)
var i Item
err := json.Unmarshal(ba, &i) // pass the pointer
fmt.Printf("%+v\n", i)
With a Reader
Using a Reader
:
var req *http.Request = ...
reader := req.Body // body implements Reader
jsonDecoder = json.NewDecoder(reader)
var s SomeStruct
if err := jsonDecoder.decode(&s); err != nil {
// ...
}
fmt.Printf("%+v\n", s)
TO PROCESS
TO PROCESS: https://golang.cafe/blog/golang-json-marshal-example.html