-
Notifications
You must be signed in to change notification settings - Fork 6
JSON
zelenko edited this page Sep 16, 2021
·
7 revisions
How to create JSON object in Go:
package main
import (
"encoding/json"
"fmt"
)
func main() {
data := make(map[string]interface{})
data["name"] = "John Doe"
data["title"] = "Golang Developer"
data["phone"] = map[string]interface{}{
"mobil": "123-456-799",
"office": "964-587-154",
}
data["email"] = "[email protected]"
jsonData, err := json.Marshal(data)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println(string(jsonData))
}
The result is:
{
"email": "[email protected]",
"name": "John Doe",
"phone": {
"mobil": "123-456-799",
"office": "964-587-154"
},
"title": "Golang Developer"
}
The same thing with formatting:
package main
import (
"encoding/json"
"fmt"
)
func main() {
data := make(map[string]interface{})
data["name"] = "John Doe"
data["title"] = "Golang Developer"
data["phone"] = map[string]interface{}{
"mobil": "123-456-799",
"office": "964-587-154",
}
data["email"] = "[email protected]"
fmt.Print(JSON(data))
}
func JSON(list interface{}) string {
result, _ := json.MarshalIndent(list, "", " ")
return string(result)
}
Read multiple objects:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
)
var j = []byte(`
{"a":1}
{"a":2}
{"a":3}
`)
func main() {
dec := json.NewDecoder(bytes.NewBuffer(j))
for {
var v interface{}
err := dec.Decode(&v)
if err == io.EOF {
break
} else if err != nil {
fmt.Println(err)
}
fmt.Println(v)
}
}
Marshal unexported fields
package main
import (
"encoding/json"
"fmt"
)
type MyStruct struct {
uuid string
Name string
}
func (m MyStruct) MarshalJSON() ([]byte, error) {
j, err := json.Marshal(struct {
Uuid string
Name string
}{
Uuid: m.uuid,
Name: m.Name,
})
if err != nil {
return nil, err
}
return j, nil
}
func main() {
myStruct := MyStruct{uuid: "71509fec-169e-11ec-9621-0242ac130002", Name: "John Doe"}
j, err := json.Marshal(myStruct)
if err != nil {
fmt.Println("Something went wrong")
return
}
fmt.Println(string(j))
}