Home >Backend Development >Golang >How to Handle Nested JSON Objects as Strings or Bytes in Go?

How to Handle Nested JSON Objects as Strings or Bytes in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-29 07:15:11656browse

How to Handle Nested JSON Objects as Strings or Bytes in Go?

Marshaling Nested JSON Objects as Strings or Bytes

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.

Problem

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

Solution

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.

Example

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

[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!

Statement:
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