[英]Unmarshalling JSON string with Golang
I have the following json string我有以下 json 字符串
{"x":{"la":"test"}} {"x":{"la":"test"}}
type Object struct {
Foo map[string]map[string]string `json:"l.a"`
}
var obj Object
err = json.Unmarshal(body, &obj)
if err != nil{
fmt.Println(err)
}
fmt.Println("jsonObj", obj)
but get empty any idea how can i get the string "test"但是让空任何想法我怎样才能得到字符串“test”
With your code Unmarshal
is looking for la
at the top level in the JSON (and it's not there - x
is).使用您的代码,
Unmarshal
正在 JSON 的顶层寻找la
(它不存在 - x
存在)。
There are a number of ways you can fix this, the best is going to depend upon your end goal;有很多方法可以解决这个问题,最好的方法取决于你的最终目标; here are a couple of them ( playground )
这里有几个(操场)
const jsonTest = `{"x":{"l.a":"test"}}`
type Object struct {
Foo map[string]string `json:"x"`
}
func main() {
var obj Object
err := json.Unmarshal([]byte(jsonTest), &obj)
if err != nil {
fmt.Println(err)
}
fmt.Println("jsonObj", obj)
var full map[string]map[string]string
err = json.Unmarshal([]byte(jsonTest), &full)
if err != nil {
fmt.Println(err)
}
fmt.Println("jsonObj2", full)
}
(Got a phone call while entering this and see @DavidLilue has provided a similar comment but may as well post this). (输入此内容时接到电话,请参阅@DavidLilue 提供了类似的评论,但不妨发布此内容)。
You can always create a struct to unmarshall your json您始终可以创建一个结构来解组您的 json
type My_struct struct {
X struct {
LA string `json:"l.a"`
} `json:"x"`
}
func main() {
my_json := `{"x":{"l.a":"test"}}`
var obj My_struct
json.Unmarshal([]byte(my_json), &obj)
fmt.Println(obj.X.LA)
}
here you are creating a struct and then unmarshalling your json string to its object, so when you do obj.X.LA
you will get the string在这里,您正在创建一个结构,然后将您的 json 字符串解组为其 object,因此当您执行
obj.X.LA
时,您将获得该字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.