cannot unmarshal string into Go struct field

后端 未结 1 1676
野性不改
野性不改 2021-01-19 09:42

I have the following (incomplete type) (which is a response from docker API from manifests endpoint v2 schema 1 https://docs.docker.com/registry/spec/manifest-v2-1/)

相关标签:
1条回答
  • 2021-01-19 10:09

    The problem is that v1Compatibility is a string value in the JSON; the value happens to be JSON content, but it's inside a JSON string, so can't be unmarshalled all in one step. You could instead unmarshal it in two passes:

    type ManifestResponse struct {
        Name         string `json:"name"`
        Tag          string `json:"tag"`
        Architecture string `json:"architecture"`
    
        FsLayers []struct {
            BlobSum string `json:"blobSum"`
        } `json:"fsLayers"`
    
        History []struct {
            V1CompatibilityRaw string `json:"v1Compatibility"`
            V1Compatibility V1Compatibility
        } `json:"history"`
    }
    
    type V1Compatibility struct {
        ID              string `json:"id"`
        Parent          string `json:"parent"`
        Created         string `json:"created"`
    }
    

    And then:

    var jsonManResp ManifestResponse
    if err := json.Unmarshal([]byte(exemplar), &jsonManResp); err != nil {
        log.Fatal(err)
    }
    for i := range jsonManResp.History {
        var comp V1Compatibility
        if err := json.Unmarshal([]byte(jsonManResp.History[i].V1CompatibilityRaw), &comp); err != nil {
            log.Fatal(err)
        }
        jsonManResp.History[i].V1Compatibility = comp
    }
    

    Working playground example here: https://play.golang.org/p/QNsu5_63E0

    0 讨论(0)
提交回复
热议问题