Cannot Unmarshal String into Go Struct Field
In attempting to deserialize a Docker API response, the error "json: cannot unmarshal string into Go struct field .v1Compatibility" occurs. The JSON structure defines a v1Compatibility field as a string, but the actual response contains a JSON string within that field.
To resolve this issue, a two-pass unmarshaling approach is required:
Here's the modified Go struct:
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"` }
After unmarshaling the raw JSON string, the V1Compatibility field can be updated with the parsed data:
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 }
This two-pass approach effectively handles the situation where a string field in the JSON response contains nested JSON content.
The above is the detailed content of How to Unmarshal Nested JSON within a String Field in Go?. For more information, please follow other related articles on the PHP Chinese website!