【问题标题】:Iterate on array of JSON objects迭代 JSON 对象数组
【发布时间】:2018-07-22 20:47:04
【问题描述】:

我刚开始学习 Go,我正在尝试遍历 JSON 对象数组的每个元素。

我尝试了以下方法。

package main

import (
    "encoding/json"
    "fmt"
)

type itemdata []string

func main() {
    var birds itemdata
    birdJson := `[{"species":"pigeon","decription":"likes to perch on rocks"},{"species":"eagle","description":"bird of prey"},{"species":"eagle","description":"bird of prey"}]`

    json.Unmarshal([]byte(birdJson), &birds)
    fmt.Println(len(birds))
    fmt.Println(birds)
    for i := range birds {
        fmt.Println(i)
        fmt.Println(birds[i])
    }

}

如何迭代每个 JSON 对象?

预期输出:

0
{"species":"pigeon","decription":"likes to perch on rocks"}
1
{"species":"eagle","description":"bird of prey"}
2
{"species":"eagle","description":"bird of prey"}

【问题讨论】:

    标签: arrays json loops go iteration


    【解决方案1】:
    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type itemdata []struct {    //Precise definition of data structure
        Species     string
        Description string
    }
    
    func main() {
        var birds itemdata
        birdJson := `[{"species":"pigeon","description":"likes to perch on rocks"},{"species":"eagle","description":"bird of prey"},{"species":"eagle","description":"bird of prey"}]`
    
        json.Unmarshal([]byte(birdJson), &birds)
        fmt.Println(len(birds))
        fmt.Println(birds)
        for i, bird := range birds {   //correct syntax for loop
            fmt.Println(i)
            fmt.Println(bird)
        }
    
    }
    

    Playground

    编辑:

    您将结构数据迭代为顺序字符串的意图看起来很不寻常。当然可以,只需构造 Decoder 和 tokenizer。

    type itemdata []json.RawMessage //delay unmarshaling of array items
    func main() {
        var birds itemdata
        birdJson := `[{"species":"pigeon","description":"likes to perch on rocks"},{"species":"eagle","description":"bird of prey"},{"species":"eagle","description":"bird of prey"}]`
        json.Unmarshal([]byte(birdJson), &birds)
        fmt.Println(len(birds))
        fmt.Println(birds)
        for i, bird := range birds {
            fmt.Println(i)
            dec := json.NewDecoder(bytes.NewReader(bird)) //construct Decoder
            for {
                t, err := dec.Token()  //Tokenise
                if err == io.EOF {
                    break
                }
                if _, ok := t.(json.Delim); !ok {
                    fmt.Println(t)
                }
            }
        }
    }
    

    Playground

    【讨论】:

    • 我希望将每个组件迭代为字符串,例如{"species":"pigeon","description":"喜欢栖息在岩石上"}
    • 我已经编辑了答案,试图实现你非常不寻常的目标
    【解决方案2】:
    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type bird struct{
        Species string
        Description string
    }
    
    func main() {
        var birds []bird
        birdJson := `[{"species":"pigeon","description":"likes to perch on rocks"},
                      {"species":"eagle","description":"bird of prey"},
                      {"species":"falcon","description":"yet another bird of prey"}]`
    
        json.Unmarshal([]byte(birdJson), &birds)
        fmt.Println(len(birds))
        fmt.Printf("\n%+v\n\n", birds)
        for i := range birds {
            fmt.Printf("%d) %s: %s\n", i, birds[i].Species, birds[i].Description)
        }
    }
    

    使用正确的循环语法:

    for i,bird := range birds {
        fmt.Printf("%d) %s: %s\n", i, bird.Species, bird.Description)
    }
    

    编辑:这是你的意思吗?

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type bird struct{
        Species string `json:"species"`
        Description string `json:"description"`
    }
    
    func main() {
        var birds []bird
        birdJson := `[{"species":"pigeon","description":"likes to perch on rocks"},
                      {"species":"eagle","description":"bird of prey"},
                      {"species":"falcon","description":"yet another bird of prey"}]`
    
        json.Unmarshal([]byte(birdJson), &birds)
        fmt.Println(len(birds))
        fmt.Printf("\n%+v\n\n", birds)
        for _,bird := range birds {
            //fmt.Printf("%d) %s: %s\n", i, bird.Species, bird.Description)
            b, _ := json.Marshal(bird)
            fmt.Println(string(b))
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      相关资源
      最近更新 更多