Iterate over json array in Go to extract values

huangapple go评论91阅读模式
英文:

Iterate over json array in Go to extract values

问题

我有一个json数组(conf.json文件)如下所示。

{
  "Repos": [
      "a",
      "b",
      "c"
  ]
}

我试图读取这个json并对其进行迭代,但卡住了。我对Go语言(以及编程)非常陌生,所以很难理解这里发生了什么。

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]

我想做的是能够迭代数组并单独拆分每个值,但是一直没有成功。我是否采取了错误的方法?有没有更好的方法来做到这一点?

英文:

I have the following in my json array (conf.json file).

{
  "Repos": [
      "a",
      "b",
      "c"
  ]
}

I am attempting to read this json and then iterate over it but get stuck. I am very new to go (and to programming) so I am having a hard time understanding what is happening here.

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)
}

So far this is as far as I have been able to get. This will print out the values okay, [a, b, c].

What I would like to do is be able to iterate over the array and split out each value individually but have not had any luck at doing this. Am I taking the wrong approach to this? Is there a better way to do this?

答案1

得分: 1

你是指这样的吗:

for _, repo := range configuration.Repos {
    fmt.Println(repo)
}

请注意,你示例中的代码在给定的 JSON 中不起作用。valueRepos 之间没有映射关系。你要么发布了不正确的 JSON,要么在 Configuration 结构体上省略了一个标签以正确映射它。

英文:

You mean something like this:

for _, repo := range configuration.Repos {
    fmt.Println(repo)
}

Note that the code in your example should not work with the JSON that you have given. There is no mapping between value and Repos. You either have posted incorrect JSON or omitted a tag on the Configuration struct to map it correctly.

答案2

得分: 0

一切都正常工作,只是你的打印输出没有按照你的期望进行。由于Repos是一个数组,你需要遍历它以逐个打印每个值。尝试像这样做:

for _, repo := range configuration.Repos {
    fmt.Println(repo)
}
英文:

Everything worked fine, it's just your printing that is not doing what you expect. Since Repos is an array you'll have to iterate it to print each value individually. Try something like this;

for _, repo := range configuration.Repos {
    fmt.Println(repo)
}

huangapple
  • 本文由 发表于 2015年7月24日 04:34:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/31597510.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定