Home >Backend Development >Golang >How to Handle Nested JSON Objects as Strings or Bytes in Go?
When Unmarshaling JSON data, it's often desirable to treat nested objects as opaque values, rather than parsing them into Go types. This can be achieved using the RawMessage type provided by the encoding/json package.
Consider the following JSON and Go struct:
{ "id": 15, "foo": { "foo": 123, "bar": "baz" } }
type Bar struct { Id int64 Foo []byte }
Attempting to Unmarshal this JSON into the Bar struct results in the following error:
json: cannot unmarshal object into Go value of type []uint8
To preserve the nested object as a string or slice of bytes, use the RawMessage type:
type Bar struct { Id int64 Foo json.RawMessage }
As described in the documentation, RawMessage is a raw encoded JSON object that implements both Marshaler and Unmarshaler interfaces.
Here's a working example:
package main import ( "encoding/json" "fmt" ) var jsonStr = []byte(`{ "id": 15, "foo": { "foo": 123, "bar": "baz" } }`) type Bar struct { Id int64 Foo json.RawMessage } func main() { var bar Bar if err := json.Unmarshal(jsonStr, &bar); err != nil { panic(err) } fmt.Printf("%+v", bar) }
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]}
[Playground link](https://play.golang.org/p/L2yJj2e72dS)
The above is the detailed content of How to Handle Nested JSON Objects as Strings or Bytes in Go?. For more information, please follow other related articles on the PHP Chinese website!