Marshall and UnMarshall JSON Content in GoLang

huangapple go评论154阅读模式
英文:

Marshall and UnMarshall JSON Content in GoLang

问题

我有一个样本的 JSON 文件,结构如下:

{
  "method":"brute_force",
  "bc":"select * from blah;",
  "gc":[
    "select sum(year) from blah;",
    "select count(*) from table;"
  ]
}

我正在尝试编写一个 Go 程序,可以读取该文件并操作其中的 JSON 内容。

package main 
import (
	"fmt"
	"encoding/json"
	"io/ioutil"
)


type Response2 struct {
    method string
    bc string
    gc []string
}

func main() {
	file,_ := ioutil.ReadFile("config.json")
	fmt.Printf("%s",string(file))

        res := &Response2{}
    

        json.Unmarshal([]byte(string(file)), &res)
        fmt.Println(res)
    
        fmt.Println(res.method)
        fmt.Println(res.gc)

}

res.method 和 res.gc 没有打印任何内容。我不知道出了什么问题。

英文:

I have a sample json file which is structured like this

{
  "method":"brute_force",
  "bc":"select * from blah;",
  "gc":[
    "select sum(year) from blah;",
    "select count(*) from table;"
      ]
}

I am trying to write a go program which can read this file and operate of json content.

package main 
import (
	"fmt"
	"encoding/json"
	"io/ioutil"
	)


type Response2 struct {
    method string
    bc string
    gc []string
}

func main() {
	file,_ := ioutil.ReadFile("config.json")
	fmt.Printf("%s",string(file))

        res := &Response2{}
    

        json.Unmarshal([]byte(string(file)), &res)
        fmt.Println(res)
    
        fmt.Println(res.method)
        fmt.Println(res.gc)

}

res.method and res.gc dont print anything. I have no idea on whats going wrong.

答案1

得分: 9

type Response2 struct {
method string
bc string
gc []string
}

字段的名称必须大写,否则Json模块无法访问它们(它们对于你的模块来说是私有的)。
你可以使用json标签来指定字段和名称之间的匹配。

type Response2 struct {
Method string json:"method"
Bc string json:"bc"
Gc []string json:"gc"
}

英文:
type Response2 struct {
    method string
    bc string
    gc []string
}

The name of the fields Must be Uppercase otherwise the Json module can't access them (they are private to your module).
You can use the json tag to specify a match between Field and name

type Response2 struct {
    Method string `json:"method"`
    Bc string `json:"bc"`
    Gc []string `json:"gc"`
}

huangapple
  • 本文由 发表于 2013年11月23日 05:13:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/20154606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定