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

How to Partially Unmarshal JSON Data into a Go Map?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-22 15:51:11539browse

How to Partially Unmarshal JSON Data into a Go Map?

How to Partially Unmarshal JSON into a Map in Go

Unmarshalling JSON data in Go can be straightforward, but challenges arise when dealing with nested objects whose keys indicate the data's type. To address this, you can leverage the "encoding/json" package.

In the provided code, you're attempting to map JSON data into a map[string][]byte, effectively converting it into a key-value pair of strings and raw JSON. However, the json.MapObject function doesn't exist, making this solution infeasible.

Instead, you can utilize a map[string]json.RawMessage to achieve your goal. RawMessage is an opaque type that holds unparsed JSON. Using this approach, the code below unmarshals the provided JSON data into the objmap variable:

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

Now, you can access the individual key-value pairs within the objmap to further parse the JSON data. For example, to parse the "sendMsg" value:

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

Similarly, you can parse the "say" value as a string:

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

Note: Remember to export the variables within your sendMsg struct to enable proper unmarshalling. For instance:

type sendMsg struct {
    User string
    Msg  string
}

You can find a working example at https://play.golang.org/p/OrIjvqIsi4-.

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