Home > Backend Development > Golang > How to Handle Nested JSON Structures and Avoid \'cannot unmarshal string into Go struct field\' Errors?

How to Handle Nested JSON Structures and Avoid \'cannot unmarshal string into Go struct field\' Errors?

DDD
Release: 2024-11-25 08:34:10
Original
220 people have browsed it

How to Handle Nested JSON Structures and Avoid

Unmarshaling JSON with Nested Structures

When working with complex JSON responses, occasionally you may encounter errors like "cannot unmarshal string into Go struct field". This typically occurs when the JSON response contains a string value that represents another JSON structure.

Consider this incomplete Go struct ManifestResponse and a corresponding JSON response:

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 {
        V1Compatibility struct {
            ID              string `json:"id"`
            Parent          string `json:"parent"`
            Created         string `json:"created"`
        } `json:"v1Compatibility"`
    } `json:"history"`
}
Copy after login
{
    "name": "library/redis",
    "tag": "latest",
    "architecture": "amd64",
    "history": [
        {
            "v1Compatibility": "{\"id\":\"ef8a93741134ad37c834c32836aefbd455ad4aa4d1b6a6402e4186dfc1feeb88\",\"parent\":\"9c8b347e3807201285053a5413109b4235cca7d0b35e7e6b36554995cfd59820\",\"created\":\"2017-10-10T02:53:19.011435683Z\"}"
        }
    ]
}
Copy after login

When attempting to unmarshal the JSON into the Go struct, you might encounter the following error:

json: cannot unmarshal string into Go struct field .v1Compatibility of type struct { ID string "json:\"id\""; Parent string "json:\"parent\""; Created string "json:\"created\"" }
Copy after login

The issue stems from the fact that v1Compatibility in the JSON response is a string value containing JSON content. To address this, we can implement a two-pass unmarshaling:

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"`
}
Copy after login

Then perform the following unmarshaling process:

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
}
Copy after login

This approach allows you to handle nested JSON structures with a two-step unmarshaling process, preventing the "cannot unmarshal string into Go struct field" error.

The above is the detailed content of How to Handle Nested JSON Structures and Avoid \'cannot unmarshal string into Go struct field\' Errors?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template