Home >Backend Development >Golang >How Can I Unmarshal Nested JSON Objects as Strings or Byte Slices in Go?

How Can I Unmarshal Nested JSON Objects as Strings or Byte Slices in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-12-17 02:18:25544browse

How Can I Unmarshal Nested JSON Objects as Strings or Byte Slices in Go?

Unmarshalling JSON Nested Objects as Strings or Byte Slices

In JSON data, nested objects provide additional levels of information. However, when unmarshalling this data into Go structures, you may want to treat these objects as raw data rather than parsed values.

To achieve this, the encoding/json package offers a solution: json.RawMessage.

Using RawMessage to Treat Nested Objects as Raw Data

json.RawMessage is a type that represents encoded JSON data. It allows you to delay JSON decoding or precompute a JSON encoding.

This is particularly useful when you want to handle nested objects as strings or byte slices. Here's how you can use it:

import (
    "encoding/json"
    "fmt"
)

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

func main() {
    // Example JSON with a nested object
    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)
}

Example 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]}

By using json.RawMessage, you can treat the nested object as a raw string or byte slice. This allows you to process the data further or store it for later use.

The above is the detailed content of How Can I Unmarshal Nested JSON Objects as Strings or Byte Slices 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