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

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

Linda Hamilton
Release: 2024-12-04 00:48:10
Original
698 people have browsed it

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

Unmarshalling Nested JSON Objects as Strings or Byte Arrays

JSON unmarshalling can be customized to handle nested objects in specific ways. In the question, the goal is to parse a JSON object, preserve a nested object as a string or byte array, and avoid automatic field assignment.

To achieve this, the encoding/json package provides the json.RawMessage type. As described in the documentation, json.RawMessage is a raw encoded JSON object that can be used to delay or precompute JSON decoding.

Here's how to use json.RawMessage to handle nested objects in the provided JSON string:

package main

import (
    "encoding/json"
    "fmt"
)

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

func main() {
    var bar Bar

    err := json.Unmarshal([]byte(`{
        "id": 15,
        "foo": { "foo": 123, "bar": "baz" }
    }`), &bar)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", bar)
}
Copy after login

In this case, the foo field of the Bar struct will contain the raw JSON bytes representing the nested object, rather than having it parsed into a Go struct. The output will look like this:

{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 using json.RawMessage, you can control how nested JSON objects are handled during unmarshalling, allowing for more flexibility in your data processing pipelines.

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