在 Golang 代码中无法访问 JSON 元素

问题描述 投票:0回答:1

我有以下 Golang 代码:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"   
    "strings"
)

func someFunc() {
    output := `
    {
        "predictions": [
          {
            "displayNames": [
              "AAA",
              "BBB",
              "CCC",
              "DDD",
              "EEE",
              "FFF",
              "GGG",
              "HHH"
            ],
            "confidences": [
              0.99998986721038818,
              5.3742646741739009e-06,
              1.7922732240549522e-06,
              1.5455394475338835e-07,
              3.2323268328582344e-07,
              6.80681324638499e-08,
              9.2994454803374538e-08,
              2.317885900993133e-06
            ],
            "ids": [
              "552624439724867584",
              "7470153467365949440",
              "6317231962759102464",
              "8911305348124508160",
              "4011388953545408512",
              "2858467448938561536",
              "5164310458152255488",
              "1705545944331714560"
            ]
          }
        ],
        "deployedModelId": "ABC123",
        "model": "myOwnModel",
        "modelDisplayName": "myDisplayName",
        "modelVersionId": "1"
    }`
    var outputJson map[string]interface{}
    json.Unmarshal([]byte(output), &outputJson)

    // names := outputJson["predictions"].(data)[0].(data)["displayNames"].(data)
    // ids := outputJson["predictions"].(data)[0].(data)["ids"].(data)
    // confidences := outputJson["predictions"].(data)[0].(data)["confidences"].(data)
    // fmt.Printf(fmt.Sprintf("Names:\n%s\n", names))
    // fmt.Printf(fmt.Sprintf("IDs:\n%s\n", ids))
    // fmt.Printf(fmt.Sprintf("Confidences:\n%s\n", confidences))

    fmt.Println("something")
}

func main() {
    someFunc()
}

我想从

displayNames
访问
ids
confidences
outputJson
元素。我使用 VS Code 来检查他们的位置,并将他们添加到监视列表中。

然后我将位置字符串复制到我的代码中。但是,它并不像图片中显示的那样工作。抱怨是

data
未定义。为什么会发生这种情况,我该怎么做才能访问这些元素?为什么这个
data
在监视窗口中有效,但在代码中却无效?

json go unmarshalling
1个回答
0
投票

你需要键入assert你的方式通过

outputJson

p := outputJson["predictions"]
if x, ok := p.([]interface{}); ok {
    if y, ok := x[0].(map[string]interface{}); ok {
        fmt.Println(y["displayNames"])
    }
}

但是,鉴于您不需要解码任意 JSON,更好的方法是定义一个 Golang 类型树,然后解组到其中:

type Output struct {
    Predictions []Prediction `json:"predictions"`
}
type Prediction struct {
    DisplayNames []string `json:"displayNames"`
    // Confidences ...
}

func main() {

    ...
    foo := &Output{}
    if err := json.Unmarshal([]byte(output), foo); err == nil {
        fmt.Println(foo.Predictions[0].DisplayNames)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.