DEV Community

Yusuf Turhan Papurcu for Golang

Posted on

6 2

Rule the JSON operations in Go 🧑‍⚖️

Have you ever wondered how much golang allows you to customize Json operations?

I searched about it and I found that we can declare our methods for json marshal/unmarshal operations. I can't guarantee this information is usable but I think it is nice to know. If you want to know how to do it please keep reading :)

Toying with Json Interfaces

I will give direct code examples in here so firstly there is our code:

package main
import (
"encoding/json"
"fmt"
)
var raw_data = `{
"FullName":"Yusuf Turhan Papurcu",
"Email":"yusufturhanp@gmail.com",
"Items":"cookie",
"CreditCardInfo":":)",
"CreatedAt":"19/03/22"
}`
func main() {
var gotData emailCover
err := json.Unmarshal([]byte(raw_data), &gotData)
fmt.Printf("%v\nerr:%s", gotData, err)
sendData := emailCover{
FullName: "Yusuf Turhan Papurcu",
Email: "yusufturhanp@gmail.com",
Items: "cookie",
CreditCardInfo: ":)",
CreatedAt: "19/03/22",
}
data_as_byte, err := json.Marshal(sendData)
fmt.Printf("%s\nerr:%s", string(data_as_byte), err)
}
type exampleStruct struct {
FullName string
Email string
Items string
CreditCardInfo string
CreatedAt string
}
func getDefaultsexamplestruct() exampleStruct {
return exampleStruct{
FullName: "N/A",
Email: "N/A",
Items: "N/A",
CreditCardInfo: "N/A",
CreatedAt: "N/A",
}
}
type emailCover exampleStruct
func (c *emailCover) UnmarshalJSON(data []byte) error {
var a exampleStruct
if err := json.Unmarshal(data, &a); err != nil {
return err
}
c.Email = a.Email
c.FullName = a.FullName
return nil
}
func (c emailCover) MarshalJSON() ([]byte, error) {
a := getDefaultsexamplestruct()
a.Email = c.Email
a.FullName = c.FullName
return json.Marshal(a)
}
view raw main.go hosted with ❤ by GitHub

Scenario: We have an exampleStruct definition at line:33. This is our user model and it's contain some problematic information in it (Like credit card info). So we want to filter them in json marshal/unmarshal.

Create new data layer

I created a type called emailCover at line:51. I need this layer because I don't want to create recursive marshaling loop in my method by using json.Marshal(). You don't need to do it but I think it is more safe for avoiding stack overflow.

Filter Coming Data in json.Unmarshal()

We implemented an UnmarshalJSON method to our cover at line:53. It basically just unmarshall all data and gives us necessary fields.

Important: Don't forget declare object as pointer in method definition.

Don't Marshal Data in json.Marshal()

We implemented an MarshalJSON method to our cover at line:64. It basically just get default version of object and just sets necessary fields. And returns json.Marshal() again. Did you notice? We put exampleStruct insde return marshal. If you try to give emailCover you cause a recursion. And this causes an stack overflow error.

Important: Don't forget declare object as value in method definition.

Extra Point

Documentation says:

Marshal traverses the value v recursively. If an encountered value implements the Marshaler interface and is not a nil pointer, Marshal calls its MarshalJSON method to produce JSON. If no MarshalJSON method is present but the value implements encoding.TextMarshaler instead, Marshal calls its MarshalText method and encodes the result as a JSON string. The nil pointer exception is not strictly necessary but mimics a similar, necessary exception in the behavior of UnmarshalJSON.

So this methods called in inheritor objects also.

Referances

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up