I develop this code:
package main
import (
"fmt"
"io/ioutil"
"encoding/json"
)
type Client struct{
host string
key string
secrete string
username string
password string
}
type Config struct{
Client []Client
}
func main(){
content, err := ioutil.ReadFile("conf2.json")
if err!=nil{
fmt.Print("Error:",err)
}
var conf Config
err=json.Unmarshal(content, &conf)
if err!=nil{
fmt.Print("Error:",err)
}
json.Unmarshal(content, &conf)
fmt.Println(conf.Client[0].host)
}
to parse and print the first host detail from my json, that looks like this:
{ "Client" : [ {"host":"192.168.1.2"},
{"key":"abcdf"}, {"secrete":"9F6w"}, {"username":"user"}, {"password":"password"} ] }
But I got an empty string. Could someone know the reason?
Here, it is the solution to my problem: package main
import (
"fmt"
"io/ioutil"
"encoding/json"
)
type Client struct {
Host string `json:"host"`
Key string `json:"apikey"`
Secret string `json:"secret"`
Username string `json:"username"`
Password string `json:"password"`
}
type Config struct {
Client Client `json:"Client"`
}
func main(){
jsonmsg, err := ioutil.ReadFile("conf2.json")
conf := new(Config)
err = json.Unmarshal([]byte(jsonmsg), &conf)
if err != nil {
fmt.Print("Error:", err)
}
fmt.Printf("%+v
%+v
%+v
%+v
%+v
", conf.Client.Host, conf.Client.Key, conf.Client.Secret, conf.Client.Username,conf.Client.Password)
}
Three things to fix:
json:"<name>"
specifier after the fields so the unmarshal knows the struct field to json mappingSee example: https://play.golang.org/p/oY7SppWNDC
Use https://github.com/Jeffail/gabs gabs library for easy manipulation of JSON
import "github.com/Jeffail/gabs"
jsonParsed, err := gabs.ParseJSON([]byte(`{
"outter":{
"inner":{
"value1":10,
"value2":22
},
"alsoInner":{
"value1":20
}
}
}`))
var value float64
var ok bool
value, ok = jsonParsed.Path("outter.inner.value1").Data().(float64)
// value == 10.0, ok == true
value, ok = jsonParsed.Search("outter", "inner", "value1").Data().(float64)
// value == 10.0, ok == true
value, ok = jsonParsed.Path("does.not.exist").Data().(float64)
// value == 0.0, ok == false
exists := jsonParsed.Exists("outter", "inner", "value1")
// exists == true
exists := jsonParsed.Exists("does", "not", "exist")
// exists == false
exists := jsonParsed.ExistsP("does.not.exist")