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:

  1. Create a map: data := make(map[string]json.RawMessage) initializes a map where keys are strings, and values are json.RawMessage.
  2. Assign values: The code assigns JSON strings as raw messages to the map using json.RawMessage('{"foo":"bar"}') and json.RawMessage('[1,2,3]').
  3. Marshal to byte slice: json.Marshal(data) encodes the map into a JSON byte slice. The err variable checks for any errors during the conversion.
  4. 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.

Golang: Convert map[string]json.RawMessage to []byte

原文地址: https://www.cveoy.top/t/topic/lAuP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录