Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Golang, what is the difference between json encoding and marshalling

Tags:

go

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?

like image 513
Scott Avatar asked Oct 11 '15 03:10

Scott


People also ask

What is marshalling in Golang?

Marshaling refers to transforming an object into a specific data format that is suitable for transmission.

What is JSON marshalling?

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.

What is JSON encoding?

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).

What is JSON encode and decode in Golang?

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.


1 Answers

  • 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.

like image 137
vinit kantrod Avatar answered Sep 25 '22 17:09

vinit kantrod