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

How to Partially Unmarshal JSON into a Go Map?

Susan Sarandon
Release: 2025-01-01 10:19:10
Original
737 people have browsed it

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"
}
Copy after login

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)
Copy after login
// 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)
Copy after login

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

type sendMsg struct {
    User string
    Msg  string
}
Copy after login

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!

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