How to unmarshal json in golang when left part is a number

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

How to unmarshal json in golang when left part is a number

问题

我想在代码中解析这样的JSON。但是这段代码不起作用。有什么建议吗?谢谢!

PS. 在这里可以找到playground:http://play.golang.org/p/m2f94LY_d_

package main

import "encoding/json"
import "fmt"

type Response struct {
    Page int
    One  string "1"
}

func main() {
    in := []byte(`{"page":1, "1":"this is 1"}`)
    res := &Response{}
    json.Unmarshal(in, &res)
    fmt.Println(res)
}
英文:

I'd like to unmarshal a json like this in the code. But this code doesn't work. Any suggestions? Thx!

PS. playground here http://play.golang.org/p/m2f94LY_d_

package main

import "encoding/json"
import "fmt"

type Response struct {
	Page int
	One  string "1"
}

func main() {
	in := []byte(`{"page":1, "1":"this is 1"}`)
	res := &Response{}
	json.Unmarshal(in, &res)
	fmt.Println(res)
}

答案1

得分: 2

你需要告诉json库json字段的名称是什么:

type Response struct {
    Page int `json:"page"`
    One  string `json:"1"`
}

在线演示:http://play.golang.org/p/CNcvQMqBGD

英文:

You need to tell the json library what the json field names are:

type Response struct {
	Page int `json:"page"`
	One  string `json:"1"`
}

Live: http://play.golang.org/p/CNcvQMqBGD

huangapple
  • 本文由 发表于 2014年8月1日 10:20:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/25071908.html
匿名

发表评论

匿名网友

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

确定