JSON Marshalling and Unmarshalling
In this article we'll see
- how to convert string data into bytes (marshal)
- how to convert bytes into Go struct (unmarshal)
- how to convert bytes into Go interface (unmarshal)
data into bytes
We coverted data into bytes in two ways:
- One, using byte() function - read function
convertToBytes
- Other, using json.Marshal() - read function
convertToBytesUsingJsonMarshal
bytes to struct
- first defined a empty struct to hold values
jb := Response{}
- then use json.Unmarshal to deserliaze into this struct
json.Unmarshal(<raw1 or raw2>,&jb)
bytes to interface
- first defined a empty interface to hold values
var jbi interface{}
- then use json.Unmarshal to deserliaze into this interface
json.Unmarshal(<raw1 or raw2>,&jbi)
Q: When to unmarshal in interface instead of struct
A: There could be many use cases. But one we found is field extraction. For example, if you are given a json with certain fields and you want to validate this json, meaning you want to make sure if it has all the required fields. SO first you need to extract all the fields right? And then match against a required fields set. Unlike Javascript we don't have the luxury to get the keys of an object by doing Object.keys() to get all keys :( So what we do? This is covered in go-json-advanced writeup.
Go Playground link https://play.golang.org/p/Fia-l18hWvi