in Golang, what is the difference between json encoding and marshalling
Solution 1:
- Marshal => String
- Encode => Stream
Marshal and Unmarshal convert a string into JSON and vice versa. Encoding and decoding convert a stream into JSON and vice versa.
The below code show working of marshal and unmarshal
type Person struct {
First string
Last string
}
func main() {
/* This will marshal the JSON into []bytes */
p1 := Person{"alice", "bob"}
bs, _ := json.Marshal(p1)
fmt.Println(string(bs))
/* This will unmarshal the JSON from []bytes */
var p2 Person
bs = []byte(`{"First":"alice","Last":"bob"}`)
json.Unmarshal(bs, &p2)
fmt.Println(p2)
}
Encoder and decoder write struct to slice of a stream or read data from a slice of a stream and convert it into a struct. Internally, it also implements the marshal method. The only difference is if you want to play with string or bytes use marshal, and if any data you want to read or write to some writer interface, use encodes and decode.
Solution 2:
Generally, encoding/decoding JSON
refers to the process of actually reading/writing the character data to a string or binary form. Marshaling/Unmarshaling refers to the process of mapping JSON
types from and to Go
data types and primitives.
Actual encoding can include things like serializing unicode characters for example. I think they may be used somewhat interchangeably in documentation sometimes because they generally occur in the same step. The Marshal function for example, will determine which JSON type to marshal something to, and then it will be encoded in string form (which may include other details such as special characters if its textual data).
You can consult the go json package docs for more details on how the marshaling/unmarshaling steps work.
Solution 3:
What is the difference between JSON 'encoding/decoding' and JSON 'marshalling/unmarshalling'?
Marshaling and Encoding are of course different concepts, better addressed on Wikipedia (or elsewhere). But in short, objects are marshaled into JSON encoded strings.
Also don't let the Golang json.NewEncoder
/ (json.Encoder).Encode
and json.Marshal
methods confuse you. They both marshal objects into JSON encoded strings. The difference being the Encoder, first marshals the object to a JSON encoded string, then writes that data to a buffer stream (or Data Buffer on Wikipedia). The Encoder therefore, uses more code and memory overhead than the simpler json.Marshal
.
You can also see this in the Golang source code:
- Marshal: https://golang.org/src/encoding/json/encode.go?s=6458:6501#L148
- Encode: https://golang.org/src/encoding/json/stream.go?s=5070:5117#L191
Typically, if you need to send the JSON encoded string to a file system, or as an HTTP response, you may need the use of a buffer stream. However, you can also send this JSON encoded string without a buffer stream using a pipe.