Jungwan Nam Jungwan Nam - 8 months ago 29
JSON Question

how to put data in struct with Golang

here is my code

package main

import "fmt"

type Species struct {
Human []Info
Animal []Info
}

type Info struct {
Name string
Number string
}

func main() {

var data Species
data = ????
fmt.Println(data)

}


i want to see json like this

{
"human":[
{"name":"dave","number":"00001"},
{"name":"jack","number":"00002"},
{"name":"nate","number":"00003"}
],
"animal":[
{"name":"ko","number":"00004"},
{"name":"na","number":"00005"}
]
}


i don't know how to put in data that struct
what do i write on '???' in code

help me
thank you

Answer Source

form json pkg you can encoding and decoding JSON format

package main

import (
    "encoding/json"
    "fmt"
)

type Species struct {
    Human  []Info `json:"human"`
    Animal []Info `json:"animal"`
}

type Info struct {
    Name   string `json:"name"`
    Number string `json:"number"`
}

func main() {
    data := Species{
        Human: []Info{
            Info{Name: "dave", Number: "00001"},
            Info{Name: "jack", Number: "00002"},
        },
        Animal: []Info{
            Info{Name: "ko", Number: "00004"},
            Info{Name: "na", Number: "00005"},
        },
    }

    b, err := json.MarshalIndent(data, "", "  ")
    if err != nil {
        fmt.Println("error:", err)
    }

    fmt.Println(string(b))
}

https://play.golang.org/p/evQto70Z8y