Golang : Save map/struct to JSON or XML file
Previous tutorial on converting map/slice/array to JSON or XML format is for output to web via net/http
package. This tutorial is a slight modification and save the output to JSON or XML file instead.
Here you go!
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"io"
"os"
"strconv"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
// create and populate a map from dummy JSON data
dataStr := `{"Name":"Dummy","Age":0}`
personMap := make(map[string]interface{})
err := json.Unmarshal([]byte(dataStr), &personMap)
if err != nil {
panic(err)
}
var onePerson Person
// convert map to Person struct
onePerson.Name = fmt.Sprintf("%s", personMap["Name"])
onePerson.Age, _ = strconv.Atoi(fmt.Sprintf("%v", personMap["Age"]))
jsonData, err := json.Marshal(onePerson)
if err != nil {
panic(err)
}
// sanity check
fmt.Println(string(jsonData))
// write to JSON file
jsonFile, err := os.Create("./Person.json")
if err != nil {
panic(err)
}
defer jsonFile.Close()
jsonFile.Write(jsonData)
jsonFile.Close()
fmt.Println("JSON data written to ", jsonFile.Name())
// write to XML file
xmlFile, err := os.Create("./Person.xml")
if err != nil {
panic(err)
}
defer xmlFile.Close()
xmlWriter := io.Writer(xmlFile)
enc := xml.NewEncoder(xmlWriter)
enc.Indent(" ", " ")
if err := enc.Encode(onePerson); err != nil {
fmt.Printf("error: %v\n", err)
}
xmlFile.Close()
fmt.Println("XML data written to ", xmlFile.Name())
}
Output:
{"name":"Dummy","age":0}
JSON data written to ./Person.json
XML data written to ./Person.xml
References:
https://www.socketloop.com/tutorials/golang-create-new-xml-file
https://www.socketloop.com/tutorials/golang-xml-to-json-example
https://www.socketloop.com/tutorials/golang-covert-map-slice-array-to-json-xml-format
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
+10.4k Golang : Select region of interest with mouse click and crop from image
+33.9k Golang : Create x509 certificate, private and public keys
+9k Golang : Serving HTTP and Websocket from different ports in a program example
+4.9k Python : Convert(cast) bytes to string example
+7k Golang : Squaring elements in array
+11.4k Golang : Display a text file line by line with line number example
+25.6k Golang : How to write CSV data to file
+16.4k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+8.6k Golang : Find duplicate files with filepath.Walk
+7.6k Golang : How to execute code at certain day, hour and minute?
+9.6k Golang : interface - when and where to use examples
+4.9k Golang : Check if a word is countable or not