encoding/json package provides json operations.
Marshalling
Marshalling means converting object to json.
Marshalling array
myArray := []string{"test 1", "test 2", "test 3"}
jsonStr, err := json.Marshal(myArray)
fmt.Println(string(jsonStr), err)
result :
["test 1","test 2","test 3"] <nil>
Marshalling Map
myMap := make(map[string]interface{})
myMap["key 1"] = "val 1"
myMap["key 2"] = "val 2"
myMap["key int"] = 1234
myMap["key bool"] = true
jsonStr, err := json.Marshal(myMap)
fmt.Println(string(jsonStr), err)
result :
{"key 1":"val 1","key 2":"val 2","key bool":true,"key int":1234} <nil>
Marshalling Object
type TestObj struct {
FieldStr string
FieldInt int
FieldMightNullString *string
SubTestObj *TestObj
}
testStr := "Might null field"
myTestObj := TestObj{
FieldStr: "test str",
FieldInt: 1,
FieldMightNullString: &testStr,
SubTestObj: &TestObj{
FieldStr: "Test str sub",
FieldInt: 2},
}
jsonStr, err := json.Marshal(myTestObj)
fmt.Println(string(jsonStr), err)
result :
{"FieldStr":"test str","FieldInt":1,"FieldMightNullString":"Might null field","SubTestObj":{"FieldStr":"Test str sub","FieldInt":2,"FieldMightNullString":null,"SubTestObj":null}} <nil>
Marshalling as human readable text (json pretty print)
MarshalIndent function provides to generate pretty printed output
...
jsonStr, err := json.MarshalIndent(myTestObj, " ", " ")
fmt.Println(string(jsonStr), err)
output :
{
"FieldStr": "test str",
"FieldInt": 1,
"FieldMightNullString": "Might null field",
"SubTestObj": {
"FieldStr": "Test str sub",
"FieldInt": 2,
"FieldMightNullString": null,
"SubTestObj": null
}
} <nil>