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
+28.3k Golang : Change a file last modified date and time
+13.3k Golang : Increment string example
+19.7k Golang : How to get time from unix nano example
+18.4k Golang : Send email with attachment
+20.4k Golang : Secure(TLS) connection between server and client
+10.6k Android Studio : Checkbox for user to select options example
+7.9k Golang : Handle Palindrome string with case sensitivity and unicode
+3.9k Detect if Google Analytics and Developer Media are loaded properly or not
+5.1k Javascript : Change page title to get viewer attention
+16.2k CodeIgniter/PHP : Create directory if does not exist example
+8.1k Prevent Write failed: Broken pipe problem during ssh session with screen command