【问题标题】:Unmarshall deep nested array in golang在 golang 中解组深层嵌套数组
【发布时间】:2021-09-22 02:02:32
【问题描述】:

我正在尝试迭代“列表”中的“内部”元素,但只恢复了最后一个“内部 - 类型”,即“c1”:

jsonData := []byte(`{
"List": [{
    "Inner":{"type":"a1"},      
    "Inner":{"type":"b1"},
    "Inner":{"type":"c1"}
}]}`)

type Test struct {
  List []struct {
    Inner struct {
      Type string `json:"type"` 
    } `json:"Inner"`
  } `json:"List"`
}

var test Test
json.Unmarshal(jsonData, &test)

fmt.Println(test.List[0].Inner.Type)

那么,有没有办法打印“列表”中的所有元素?

【问题讨论】:

    标签: go arraylist unmarshalling


    【解决方案1】:

    您可能需要确定 []List 对象内的对象的类型,并使用自定义逻辑实现 JSONUnmarshaller 接口,如下所示。

    package main
    
    import (
        "encoding/json"
        "fmt"
        "regexp"
        "strings"
    )
    
    type Inner struct{
        Type string `json:"type"`
    }
    
    type List []Inner
    
    type Test struct {
        List [] List `json:"List"`
    }
    
    func main() {
        jsonData := []byte(`{
    "List": [{
        "Inner":{"type":"a1"},      
        "Inner":{"type":"b1"},
        "Inner":{"type":"c1"}
    }]}`)
    
        var test Test
        err := json.Unmarshal(jsonData, &test)
        if err != nil{
            fmt.Println(err)
            return
        }
    
        for _,v := range test.List[0]{
            fmt.Println(v.Type)
        }
    }
    
    func (l *List) UnmarshalJSON(bytes []byte) error {
        out := make(List,0)
        re := regexp.MustCompile(`"Inner":{.*}`)
        objects := re.FindAll(bytes,-1)
        for _,v := range objects{
            inner := Inner{}
            s := strings.TrimLeft(string(v),`"Inner":`)
            err := json.Unmarshal([]byte(s),&inner)
            if err != nil{
                return err
            }
            out = append(out,inner)
        }
        *l = out
        return nil
    }
    

    输出:

    a1
    b1
    c1
    

    【讨论】:

      【解决方案2】:

      您不能在 JSON 中的同一个对象上有多个相同的键:

      console.log(JSON.parse(`{
          "Inner":{"type":"a1"},      
          "Inner":{"type":"b1"},
          "Inner":{"type":"c1"}
      }`))

      所以无需编写自定义解组器,不。

      【讨论】:

      • JSON spec可以拥有重复的键 - 但是...When the names within an object are not unique, the behavior of software that receives such an object is unpredictable. Many implementations report the last name/value pair only. Other implementations report an error or fail to parse the object, and some implementations report all of the name/value pairs, including duplicates.
      猜你喜欢
      • 2020-12-10
      • 1970-01-01
      • 2018-01-25
      • 2019-01-13
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 2020-12-15
      • 2016-03-01
      相关资源
      最近更新 更多