douwaz34842 2017-06-17 16:34
浏览 109
已采纳

从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

  • 写回答

1条回答 默认 最新

  • dongmi19720408 2017-06-17 17:05
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB代码补全插值
  • ¥15 Typegoose 中如何使用 arrayFilters 筛选并更新深度嵌套的子文档数组信息
  • ¥15 前后端分离的学习疑问?
  • ¥15 stata实证代码答疑
  • ¥50 husky+jaco2实现在gazebo与rviz中联合仿真
  • ¥15 dpabi预处理报错:Error using y_ExtractROISignal (line 251)
  • ¥15 在虚拟机中配置flume,无法将slave1节点的文件采集到master节点中
  • ¥15 husky+kinova jaco2 仿真
  • ¥15 zigbee终端设备入网失败
  • ¥15 金融监管系统怎么对7+4机构进行监管的