Home > Backend Development > Golang > How to Unmarshal JSON Nested Objects as Byte Arrays in Go?

How to Unmarshal JSON Nested Objects as Byte Arrays in Go?

Linda Hamilton
Release: 2024-12-02 15:13:12
Original
419 people have browsed it

How to Unmarshal JSON Nested Objects as Byte Arrays in Go?

Unmarshalling JSON Nested Objects as Strings or Byte Arrays

When dealing with JSON responses, it may be necessary to preserve certain nested objects as raw strings or byte arrays instead of having them parsed into Go structures. To address this, we will explore a solution using the json.RawMessage type from the encoding/json package.

In your specific scenario, the following JSON:

{
    "id"  : 15,
    "foo" : { "foo": 123, "bar": "baz" }
}
Copy after login

was to be unmarshalled into a Go structure with an ID field of type int64 and a Foo field of type []byte. The error you encountered, "json: cannot unmarshal object into Go value of type []uint8," indicates that the unmarshalling process was attempting to parse the foo object into a Go value, which is not intended behavior.

The json.RawMessage type provides a solution for this problem. As its documentation states, it is "a raw encoded JSON object" that can be used to delay JSON decoding or precompute a JSON encoding. Using json.RawMessage, you can effectively preserve the foo object as a raw byte array in your Go structure:

import (
    "encoding/json"
    "fmt"
)

type Bar struct {
    ID  int64           `json:"id"`
    Foo json.RawMessage `json:"foo"`
}

func main() {
    var jsonStr = []byte(`{
    "id"  : 15,
    "foo" : { "foo": 123, "bar": "baz" }
}`)

    var bar Bar

    err := json.Unmarshal(jsonStr, &bar)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", bar)
}
Copy after login

Output:

{Id:15 Foo:[123 32 34 102 111 111 34 58 32 49 50 51 44 32 34 98 97 114 34 58 32 34 98 97 122 34 32 125]}
Copy after login

By leveraging json.RawMessage, you can now successfully Unmarshal the JSON into a Go structure that treats the foo object as a byte array.

The above is the detailed content of How to Unmarshal JSON Nested Objects as Byte Arrays in Go?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template