{ "@context": "https://schema.org", "@type": "Article", "headline": "无法在Golang中读取JSON元素的值", "datePublished": "2024-02-08T17:45:22", "dateModified": "2024-02-08T17:45:22", "description": "今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《无法在Golang中读取JSON元素的值》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!问题内容我有以下 golang 代码:package mainimport ( bytes encoding/json fmt strings)func someFunc() { output := ` { ", "publisher": { "@type": "Organization", "name": "Golang学习网", "url": "https://m.17golang.com" }, "mainEntityOfPage": { "@type": "WebPage", "@id": "https://m.17golang.com/article/94796.html" } }
登录
首页 >  Golang >  Go问答

无法在Golang中读取JSON元素的值

来源:stackoverflow

时间:2024-02-08 17:45:22 319浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《无法在Golang中读取JSON元素的值》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我有以下 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()
}

我想从 outputjson 访问 displaynamesidsconfidences 元素。我使用 vs code 检查它们的位置,并将它们添加到监视列表中。

然后,我将位置字符串复制到我的代码中。但是,它不起作用,如图所示。抱怨是 data 未定义。为什么会发生这种情况?我该怎么做才能访问这些元素?为什么这个 data 在监视窗口中有效,但在代码中无效?


正确答案


您需要通过 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)
    }
}

以上就是《无法在Golang中读取JSON元素的值》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>