Home >Backend Development >Golang >How to Efficiently Parse Partially a JSON Map in Go?

How to Efficiently Parse Partially a JSON Map in Go?

Susan Sarandon
Susan SarandonOriginal
2024-12-26 07:45:09255browse

How to Efficiently Parse Partially a JSON Map in Go?

Parsing JSON Data into a Map in Go

Websocket servers often receive JSON data wrapped in key-value pairs that indicate the type of value. While the "encoding/json" package provides convenient unmarshalling capabilities, there is a need to parse the JSON data partially into a map for further processing.

Approach Using a map[string]json.RawMessage

To achieve partial unmarshalling, one can utilize a map[string]json.RawMessage. This approach allows the JSON data to be unmarshaled into a map, with the keys being the property names and the values being the unparsed JSON data.

import (
    "encoding/json"
    "fmt"
)

func main() {
    data := []byte(`{"sendMsg":{"user":"ANisus","msg":"Trying to send a message"},"say":"Hello"}`)

    var objmap map[string]json.RawMessage
    err := json.Unmarshal(data, &objmap)
    if err != nil {
        fmt.Printf("Error unmarshaling JSON: %v", err)
        return
    }

    // Unpack Individual Values

    // Parsing sendMsg
    var s sendMsg
    err = json.Unmarshal(objmap["sendMsg"], &s)
    if err != nil {
        fmt.Printf("Error unmarshaling 'sendMsg': %v", err)
        return
    }
    fmt.Println("sendMsg:", s)

    // Parsing say
    var str string
    err = json.Unmarshal(objmap["say"], &str)
    if err != nil {
        fmt.Printf("Error unmarshaling 'say': %v", err)
        return
    }
    fmt.Println("say:", str)
}

type sendMsg struct {
    User string
    Msg  string
}

In this approach, the objmap will contain a key "sendMsg" with a value that is the raw JSON data representing the sendMsg object. By further unmarshaling this data into a sendMsg struct, the individual fields (User and Msg) can be accessed.

Note: To ensure successful unmarshalling, remember to export the fields in the sendMsg struct (i.e., User and Msg).

The above is the detailed content of How to Efficiently Parse Partially a JSON Map in Go?. 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