Difference of Json Encoding vs Marshaling and json decoding vs UnMarshaling

Dinesh Silwal
wesionaryTEAM
Published in
3 min readApr 18, 2022

--

Data encoding | decoding is an important part of any programming language to encode data into JSON or decode data into String, means it is equally important concept in Golang.

  1. UseCase is how to convert from JSON raw data (strings or bytes) into Go types like structs, arrays, and slices, as well as unstructured data like maps and empty interfaces and vice versa.
    To understand it’s use case , Let read remaining articles below :-

- First Understand, Marshaling and Encoding are course of different concepts .
- 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 .The Encoder therefore, uses more code and memory overhead than the simpler json.Marshal.

-Encoding/decoding JSON refers to the process of actually reading/writing the character data to a string or binary form.

- Marshaling/Un marshaling refers to the process of mapping JSON types from and to Go data types and primitives.

- In Golang, struct data is converted into JSON using Marshal() and JSON data to string using Un marshal() method.

1. UnMarshaling or consuming Json Data

The Unmarshal function provided by Go’s JSON standard library lets us parse raw JSON data in the form of []byte variables.

  • We convert JSON strings into bytes and un marshal the data into a variables address
  • `&decodedCourse ` is the address of the variable where we want to store our parsed data in.

2. Marshaling or creating Json Data

In above code, Json.Marshal() return , finalJson as the Json string, represented as bytes, and second parameter here is the error Which should be ideally handle.

fig : Output in json format

3. Encoding JSON : writing | creating data

Steps to understand codebase :
1. Create buffer
2. Marshal object to json using Encode behind the scenes (marshal() is called)
3. Store json encoded data into buffer using NewEncoder(buff)
4. Create json file
5. Copy from buffer to json file

fig : coursedb.json

4. Decoding JSON | Reading data

fig : Decoding Json data

We see how Use Case differs for Marshaling and Encoding. Let’s conclude articles

The conclusion of the article is :

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.

--

--