Home > Backend Development > Golang > How Can I Partially Decode and Update JSON in Go While Preserving Unknown Fields?

How Can I Partially Decode and Update JSON in Go While Preserving Unknown Fields?

Patricia Arquette
Release: 2024-12-31 10:28:10
Original
525 people have browsed it

How Can I Partially Decode and Update JSON in Go While Preserving Unknown Fields?

Partial Decoding and Updating of JSON in Go

When working with JSON objects, it may be necessary to decode only specific values while preserving unknown portions of the object. The encoding/json package in Go, however, tends to truncate fields not present in the struct, leading to data loss when re-encoding.

A Solution

To overcome this issue, a combination of a simple struct and json.RawMessage can be used to preserve unknown fields.

type Color struct {
    Space string
    raw   map[string]json.RawMessage
}
Copy after login

In this struct, the raw field stores the entire JSON object as a RawMessage. When decoding, the UnmarshalJSON method reads the raw field to extract specific values into the struct's defined fields.

func (c *Color) UnmarshalJSON(bytes []byte) error {
    if err := json.Unmarshal(bytes, &c.raw); err != nil {
        return err
    }
    if space, ok := c.raw["Space"]; ok {
        if err := json.Unmarshal(space, &c.Space); err != nil {
            return err
        }
    }
    return nil
}
Copy after login

Similarly, when encoding, the MarshalJSON method serializes the Space field and updates the raw map with the encoded bytes.

func (c *Color) MarshalJSON() ([]byte, error) {
    bytes, err := json.Marshal(c.Space)
    if err != nil {
        return nil, err
    }
    c.raw["Space"] = json.RawMessage(bytes)
    return json.Marshal(c.raw)
}
Copy after login

This approach allows for partial decoding and updating of specific fields, while preserving the unknown portions of the JSON object.

The above is the detailed content of How Can I Partially Decode and Update JSON in Go While Preserving Unknown Fields?. 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