Golang : Covert map/slice/array to JSON or XML format
Problem :
You have a data struct in map, slice or array format and you have to convert the data to JSON or XML format. How to do that?
Solution :
Convert the map, slice or array data to JSON with json.Marshal()
function. In the struct, remember to add struct tags for JSON or XML.
NOTE : Set Content-Type to application/json or application/xml when writing out as HTTP response.
For example :
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type KeyPair struct {
Id int `json:"id"` // <--- json struct tags
Name string `json:"name"` // <--- json struct tags
}
func Home(w http.ResponseWriter, r *http.Request) {
KP := KeyPair{Id: 1, Name: "Adam"}
fmt.Println(KP)
byte, err := json.Marshal(KP) // <---- here !
if err != nil {
return
}
w.Header().Set("Content-Type", "application/json") // <---- here !
fmt.Fprint(w, string(byte))
fmt.Println(string(byte))
}
func main() {
http.HandleFunc("/", Home)
http.ListenAndServe(":8080", nil)
}
To convert struct data to XML, just change the encoder and field tags to XML equivalent. See https://www.socketloop.com/tutorials/golang-xml-to-json-example for guide.
Happy coding!
See also : Golang : XML to JSON example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.8k Golang : Check if a word is countable or not
+19.8k Golang : Compare floating-point numbers
+11.2k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+9.9k Golang : Compare files modify date example
+6.7k Golang : Normalize email to prevent multiple signups example
+15k Golang : How to get Unix file descriptor for console and file
+20.8k Golang : Clean up null characters from input data
+8.7k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+29k Golang : Record voice(audio) from microphone to .WAV file
+5.1k Golang : Return multiple values from function
+9.5k Golang : List available AWS regions