« Back to Index

Go: combine two structs with json.Marshal

View original Gist on GitHub

Tags: #go #json #serialization

combine two structs for json marshal.go

package main

import (
	"encoding/json"
	"fmt"
)

type A struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	URL         string `json:"url"`
}

type B struct {
	Name string `json:"name"`
	*A
}

func main() {
	a := A{Name: "test", Description: "desc", URL: "https://example.com"}
	b := B{Name: "new name"}

	b.A = &a

	data, _ := json.Marshal(b)

	fmt.Println(string(data))
}