I have the following json string
{"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"
With your code Unmarshal
is looking for la
at the top level in the JSON (and it's not there - x
is).
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).
You can always create a struct to unmarshall your 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.