在 Go 中迭代 json 数组以提取值

我的 json 数组(conf.json 文件)中有以下内容。


{

  "Repos": [

      "a",

      "b",

      "c"

  ]

}

我正在尝试读取此 json,然后对其进行迭代但卡住了。我对去(和编程)很陌生,所以我很难理解这里发生的事情。


import (

    "encoding/json"

    "fmt"

    "os"

)


type Configuration struct {

    Repos []string

}


func read_config() {

    file, _ := os.Open("conf.json")

    decoder := json.NewDecoder(file)

    configuration := Configuration{}

    err := decoder.Decode(&configuration)

    if err != nil {

        fmt.Println("error:", err)

    }


    fmt.Println(configuration.Repos)

}

到目前为止,这是我所能得到的。这将打印出值,好的[a, b, c]。


我想要做的是能够遍历数组并单独拆分每个值,但在这样做时没有任何运气。我对此采取了错误的方法吗?有一个更好的方法吗?


慕莱坞森
浏览 287回答 2
2回答

慕标5832272

你的意思是这样的:for _, repo := range configuration.Repos {    fmt.Println(repo)}请注意,您的示例中的代码不应与您提供的 JSON 一起使用。value和之间没有映射Repos。您要么发布了不正确的 JSON,要么在Configuration结构上省略了一个标记以正确映射它。

ibeautiful

一切正常,只是您的打印没有达到您的预期。由于 Repos 是一个数组,因此您必须对其进行迭代以单独打印每个值。尝试这样的事情;for _, repo := range configuration.Repos {    fmt.Println(repo)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go