Struct2Json
offers the ability to convert Struct
to map[string]interface{}
directly
I support json
tag & noroot
tag to help us organize our output JSON
see examples below
go get github.com/w-zengtao/struct2json
type AStruct struct {
A int `json:"a"`
}
type BStruct struct {
B int `json:"b"`
}
type CStruct struct {
C int
D *int
E *int
AS AStruct `json:"as"`
BS BStruct `json:"bs"`
ASP *AStruct
BSP *BStruct
ASNoroot AStruct `json:"asnoroot" noroot:"true"`
}
var (
i = 10
)
input := CStruct{
C: 1,
D: &i,
AS: AStruct{
A: 1,
},
BSP: &BStruct{
B: 1,
},
ASNoroot: AStruct{
A: 100,
},
}
struct2json.Convert(input)
{
ASP: nil, // nil pointer
BSP: {
b: 1
},
C: 1,
D: 10, // *int
E: nil,
a: 100, // ASNoroot
as: {
a: 1
},
bs: {
b: 0
}
}
- Only
pointer
can have nil value, so if you do not want theGo's default value
, use pointer field. - Only
struct
orpointer to struct
supportnoroot
tag - Once
noroot
meet same json tag, areplace
action will be happend
© w-zengtao, 2019~time.Now
Released under the MIT License