Home >Backend Development >Golang >How Can I Partially Unmarshal JSON into a Go Map?

How Can I Partially Unmarshal JSON into a Go Map?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-26 04:28:09293browse

How Can I Partially Unmarshal JSON into a Go Map?

Partially JSON Unmarshal into a Map in Go

In Go, it's possible to partially unmarshal JSON data into a map when the data is wrapped in an object with key-value pairs. This allows for easy identification of the type of value each key holds.

Implementation

To achieve this, use the encoding/json package and unmarshal into a map[string]json.RawMessage. The json.RawMessage type captures the underlying JSON data before further parsing.

var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)

Further Parsing

Once the map is obtained, you can proceed to parse the value of each key according to its known type.

For the example JSON:

{
    "sendMsg":{"user":"ANisus","msg":"Trying to send a message"},
    "say":"Hello"
}

You can parse sendMsg and say as follows:

type sendMsg struct {
    User string
    Msg  string
}

var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)

var str string
err = json.Unmarshal(objmap["say"], &str)

Exporting Variables

Note that the variables in the sendMsg struct must be exported (i.e., capitalized) for proper unmarshaling, as shown:

type sendMsg struct {
    User string
    Msg  string
}

Example

See a working example here: https://play.golang.org/p/OrIjvqIsi4-

The above is the detailed content of How Can I Partially Unmarshal JSON into a Go Map?. 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