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

How to Partially Unmarshal JSON into a Go Map?

Susan Sarandon
Susan SarandonOriginal
2025-01-01 10:19:10793browse

How to Partially Unmarshal JSON into a Go Map?

Unmarshalling Partial JSON into a Map in Go

Partially unmarshalling JSON data into a map can be useful when the JSON is structured in a specific way, with a key-value structure where the key identifies the type of value. This approach enables efficient processing and type-specific handling of the data.

Consider the following JSON example:

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

To parse this JSON using the "encoding/json" package, you can unmarshal it into a map of strings to JSON "RawMessage" objects:

var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)
// Accessing the "sendMsg" value:
var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)

// Accessing the "say" value:
var str string
err = json.Unmarshal(objmap["say"], &str)

To unmarshal into specific data types, you need to export the struct fields in your sendMsg struct:

type sendMsg struct {
    User string
    Msg  string
}

This approach provides flexibility in handling JSON data with varying structures and allows for type-safe unmarshalling based on the key in the JSON object.

The above is the detailed content of How to 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