douxu2081
2016-02-23 22:29
浏览 166

Golang中的JSON解析错误

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?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongxi8297 2016-02-24 21:21
    已采纳

    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)
    }
    
    已采纳该答案
    打赏 评论
  • dongmeng1402 2016-02-23 23:10

    Three things to fix:

    • json.Unmarshal requires the struct fields to be capitalized to be exported or they are ignored
    • You need the json:"<name>" specifier after the fields so the unmarshal knows the struct field to json mapping
    • Your json was making multiple clients with one field filled in instead of one client with all the fields filled in

    See example: https://play.golang.org/p/oY7SppWNDC

    打赏 评论
  • dsegw3424 2016-02-24 12:48

    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")
    
    打赏 评论

相关推荐 更多相似问题