Home >Backend Development >Golang >How to Handle Nested JSON Strings When Unmarshaling in Go?
Unmarshaling JSON with Nested Strings
When encountering an error stating "cannot unmarshal string into Go struct field," it signifies that the JSON being parsed contains a string value within a field that is expected to be a struct. To resolve this issue, consider the following approach:
import ( "encoding/json" "fmt" "log" ) 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"` } func main() { exemplar := `{ "schemaVersion": 1, "name": "library/redis", "tag": "latest", "architecture": "amd64", "history": [ { "v1Compatibility": "{\"id\":\"ef8a93741134ad37c834c32836aefbd455ad4aa4d1b6a6402e4186dfc1feeb88\",\"parent\":\"9c8b347e3807201285053a5413109b4235cca7d0b35e7e6b36554995cfd59820\",\"created\":\"2017-10-10T02:53:19.011435683Z\"}" } ] } ` 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 } fmt.Println(jsonManResp) }
In this updated code, we declare V1CompatibilityRaw as a string field within ManifestResponse.History and then manually unmarshal it into a V1Compatibility struct.
This approach allows proper deserialization of the JSON response into the desired Go struct, ensuring that the nested string is parsed correctly.
The above is the detailed content of How to Handle Nested JSON Strings When Unmarshaling in Go?. For more information, please follow other related articles on the PHP Chinese website!