Golang: Convert map[string]json.RawMessage to []byte
Converting Golang map[string]json.RawMessage to []byte
You can use the json.Marshal function to convert a map[string]json.RawMessage type to a []byte type in Golang.
Example Code:
package main
import (
"encoding/json"
"fmt"
)
func main() {
data := make(map[string]json.RawMessage)
data['key1'] = json.RawMessage('{"foo":"bar"}')
data['key2'] = json.RawMessage('[1,2,3]')
b, err := json.Marshal(data)
if err != nil {
panic(err)
}
fmt.Println(string(b))
}
Output:
{"key1":{"foo":"bar"},"key2":[1,2,3]}
Explanation:
- Create a map:
data := make(map[string]json.RawMessage)initializes a map where keys are strings, and values arejson.RawMessage. - Assign values: The code assigns JSON strings as raw messages to the map using
json.RawMessage('{"foo":"bar"}')andjson.RawMessage('[1,2,3]'). - Marshal to byte slice:
json.Marshal(data)encodes the map into a JSON byte slice. Theerrvariable checks for any errors during the conversion. - Print the result:
fmt.Println(string(b))prints the JSON byte slice as a string, showcasing the final output.
In conclusion: To convert a map[string]json.RawMessage to a []byte type, simply use the json.Marshal function. This straightforward process enables you to work with JSON data effectively in your Golang projects.
原文地址: https://www.cveoy.top/t/topic/lAuP 著作权归作者所有。请勿转载和采集!