Golang JSON Marshal a Struct With Pointers

Simplify Complexity
1 min readApr 17, 2021
package main

import (

type Num struct {
N int

type Packed struct {
Num *Num
Name string

func main() {
num := &Num{N: 100}

packed := Packed{pNum: num, Name: "xx-packed-xy"}

dataInBytes, err := json.Marshal(packed)
fmt.Printf("%+v data=%s\n", err, string(dataInBytes))

unpacked := &Packed{}
err = json.Unmarshal(dataInBytes, unpacked)
fmt.Printf("%v, %+v\n", err, unpacked)

The above code marshals an object of type struct using a pointer. The code does not work as expected. That means the unmarshalled object does…



Simplify Complexity

Golang, Distributed Systems, File Systems, Python, C/C++, Linux