[英]How to access key and value from json in golang?
I have a struct 我有一个结构
type Order struct {
ID string `json:"id"`
CustomerMobile string `json:"customerMobile"`
CustomerName string `json:"customerName"`
}
and the json data: 和json数据:
[{"Key":"S001", "Record":{"id":"SOO1","customerMobile":"12344566","customerName":"John"}}]
How can i access customerMobile key from the above json object? 如何从上述json对象访问customerMobile密钥?
I have done some research in Google and i found the below solution, but its not working when i apply to my above requirement. 我在Google上进行了一些研究,发现了以下解决方案,但是当我满足上述要求时,它不起作用。 Its working with simple json format. 它使用简单的json格式。
jsonByteArray := []byte(jsondata)
json.Unmarshal(jsonByteArray, &order)
You need to unmarshal into something that represents the entire JSON object. 您需要解组成代表整个JSON对象的内容。 Your Order
struct defines part of it, so just define the rest of it, as follows: 您的Order
结构定义了它的一部分,所以只需定义它的其余部分,如下所示:
package main
import (
"encoding/json"
"fmt"
)
type Order struct {
ID string `json:"id"`
CustomerMobile string `json:"customerMobile"`
CustomerName string `json:"customerName"`
}
type Thing struct {
Key string `json:"Key"`
Record Order `json:"Record"`
}
func main() {
jsonByteArray := []byte(`[{"Key":"S001", "Record":{"id":"SOO1","customerMobile":"12344566","customerName":"John"}}]`)
var things []Thing
err := json.Unmarshal(jsonByteArray, &things)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", things)
}
Give a try to this: https://play.golang.org/p/pruDx70SjW 尝试一下: https : //play.golang.org/p/pruDx70SjW
package main
import (
"encoding/json"
"fmt"
)
const data = `[{"Key":"S001", "Record":{"id":"SOO1","customerMobile":"12344566","customerName":"John"}}]`
type Orders struct {
Key string
Record Order
}
type Order struct {
ID string
CustomerMobile string
CustomerName string
}
func main() {
var orders []Orders
if err := json.Unmarshal([]byte(data), &orders); err != nil {
panic(err)
}
fmt.Printf("%+v\n", orders)
}
In this case, I am omitting the struct tags 在这种情况下,我省略了struct标签
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.