Home > Backend Development > Golang > How to Decode Nested JSON Objects into Raw Data in Go?

How to Decode Nested JSON Objects into Raw Data in Go?

Patricia Arquette
Release: 2024-12-06 16:48:15
Original
214 people have browsed it

How to Decode Nested JSON Objects into Raw Data in Go?

JSON Decoding Nested Objects into Raw Data

In the world of JSON decoding, there are times when you may encounter a nested object that you don't need to fully parse. Instead, you might prefer to treat it as a raw string or byte array. Here's a sample code demonstrating this approach:

package main

import (
    "encoding/json"
    "fmt"
)

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

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

    var bar Bar

    if err := json.Unmarshal(jsonStr, &bar); err != nil {
        panic(err)
    }

    fmt.Printf("%+v\n", bar)
}
Copy after login

In this example, the Bar struct contains two fields: ID and Foo. The ID field is an int64, while the Foo field is declared as a json.RawMessage. This type allows us to hold the JSON bytes associated with the nested object.

When decoding the JSON, the RawMessage field will store the raw JSON bytes representing the nested object. This includes any nested fields within that object, allowing you to access them later if needed.

This approach is useful when you want to postpone parsing specific portions of the JSON to save computational resources. It also provides greater flexibility in handling nested objects without the need to define custom types for each object.

The above is the detailed content of How to Decode Nested JSON Objects into Raw Data 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