从JSON字符串中检索数组元素的值的最佳方法是什么
问题描述:
Trying to retrieve value "default-token-k99mq" from below JSON in go program ...
const input = `{
"kind": "ServiceAccount",
"apiVersion": "v1",
"metadata": {
"name": "default",
"namespace": "mynamespace",
"selfLink": "/api/v1/namespaces/mynamespace/serviceaccounts/default",
"uid": "483d1043-4d68-11e7-be08-3a3f3b149220",
"resourceVersion": "425039",
"creationTimestamp": "2017-06-09T23:06:34Z"
},
"secrets": [
{
"name": "default-token-k99mq"
}
]
}`
Need to get names from secrets
array
试图在go程序中从JSON下面检索值“ default-token-k99mq” ... p>
const input ='{
“ kind”:“ ServiceAccount”,
“ apiVersion”:“ v1”,
“ metadata”:{
“ name”:“默认 “,
” namespace“:” mynamespace“,
” selfLink“:” / api / v1 / namespaces / mynamespace / serviceaccounts / default“,
” uid“:” 483d1043-4d68-11e7-be08-3a3f3b149220“ ,
“ resourceVersion”:“ 425039”,
“ creationTimestamp”:“ 2017-06-09T23:06:34Z”
},
“ secrets”:[
{
“ name”:“默认 -token-k99mq“
}
]
}`
code> pre>
需要从 secrets code>数组 p>中获取名称
div>
答
You can do this https://play.golang.org/p/27eKFmBCHY
package main
import (
"fmt"
"encoding/json"
)
func main() {
const input = `{
"kind": "ServiceAccount",
"apiVersion": "v1",
"metadata": {
"name": "default",
"namespace": "mynamespace",
"selfLink": "/api/v1/namespaces/mynamespace/serviceaccounts/default",
"uid": "483d1043-4d68-11e7-be08-3a3f3b149220",
"resourceVersion": "425039",
"creationTimestamp": "2017-06-09T23:06:34Z"
},
"secrets": [
{
"name": "default-token-k99mq"
}
]
}`
type NameStruct struct {
Name string `json:"name"`
}
type Secret struct {
Secrets []NameStruct `json:"secrets"`
}
secret := Secret{}
json.Unmarshal([]byte(input), &secret)
fmt.Println(secret.Secrets[0].Name)
}