在Golang中使用JSON解析时出错

时间:2016-02-23 22:29:36

标签: json parsing go

我开发了这段代码:

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)
}

从我的json中解析并打印第一个主机细节,如下所示:

  

{         "客户" :         [             {"主机":" 192.168.1.2"},
            {"键":" ABCDF"},             {"分泌":" 9F6w"},             {"用户名":"用户"},             {"密码":"密码"}         ]       }

但我得到一个空字符串。有人知道原因吗?

3 个答案:

答案 0 :(得分:4)

要解决的三件事:

  • json.Unmarshal要求将struct字段大写导出或忽略它们
  • 在字段后面需要json:"<name>"说明符,因此unmarshal知道结构字段为json映射
  • 您的json正在制作多个客户端,其中填写了一个字段而不是一个客户端,其中填写了所有字段

参见示例:https://play.golang.org/p/oY7SppWNDC

答案 1 :(得分:1)

在这里,它是我的问题的解决方案:     包主要

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\n%+v\n%+v\n%+v\n%+v\n", conf.Client.Host, conf.Client.Key, conf.Client.Secret, conf.Client.Username,conf.Client.Password)
}

答案 2 :(得分:0)

使用https://github.com/Jeffail/gabs gabs库,便于操作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")