What is the difference between JSON 'encoding/decoding' and JSON 'marshalling/unmarshalling'?
Trying to learn how to write a RESTFUL api in golang and not sure what the difference between JSON 'encoding' and 'marshalling' is or if they are the same?
Marshaling refers to transforming an object into a specific data format that is suitable for transmission.
JSON has 3 basic types: booleans, numbers, strings, combined using arrays and objects to build complex structures. Go's terminology calls marshal the process of generating a JSON string from a data structure, and unmarshal the act of parsing JSON to a data structure.
The default encoding is UTF-8, and JSON texts that are encoded in UTF-8 are interoperable in the sense that they will be read successfully by the maximum number of implementations; there are many implementations that cannot successfully read texts in other encodings (such as UTF-16 and UTF-32).
JSON is a widely used format for data interchange. Golang provides multiple encoding and decoding APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. Data Types: The default Golang data types for decoding and encoding JSON are as follows: bool for JSON booleans.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With