Golang : XML to JSON example
For this tutorial, we will learn how to read data from XML file, process the data and save the output to JSON format. Converting XML to JSON data format can be done easily with the Golang's encoding/xml
and encoding/json
packages.
Create the Employees.xml file with this content :
<?xml version="1.0"?>
<company>
<staff>
<id>101</id>
<firstname>Derek</firstname>
<lastname>Young</lastname>
<username>derekyoung</username>
</staff>
<staff>
<id>102</id>
<firstname>John</firstname>
<lastname>Smith</lastname>
<username>johnsmith</username>
</staff>
</company>
and the code to eat this XML data and poop out JSON file :
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
type jsonStaff struct {
ID int
FirstName string
LastName string
UserName string
}
type Staff struct {
XMLName xml.Name `xml:"staff"`
ID int `xml:"id"`
FirstName string `xml:"firstname"`
LastName string `xml:"lastname"`
UserName string `xml:"username"`
}
type Company struct {
XMLName xml.Name `xml:"company"`
Staffs []Staff `xml:"staff"`
}
func (s Staff) String() string {
return fmt.Sprintf("\t ID : %d - FirstName : %s - LastName : %s - UserName : %s \n", s.ID, s.FirstName, s.LastName, s.UserName)
}
func main() {
xmlFile, err := os.Open("Employees.xml")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer xmlFile.Close()
XMLdata, _ := ioutil.ReadAll(xmlFile)
var c Company
xml.Unmarshal(XMLdata, &c)
// sanity check - XML level
fmt.Println(c.Staffs)
// convert to JSON
var oneStaff jsonStaff
var allStaffs []jsonStaff
for _, value := range c.Staffs {
oneStaff.ID = value.ID
oneStaff.FirstName = value.FirstName
oneStaff.LastName = value.LastName
oneStaff.UserName = value.UserName
allStaffs = append(allStaffs, oneStaff)
}
jsonData, err := json.Marshal(allStaffs)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// sanity check - JSON level
fmt.Println(string(jsonData))
// now write to JSON file
jsonFile, err := os.Create("./Employees.json")
if err != nil {
fmt.Println(err)
}
defer jsonFile.Close()
jsonFile.Write(jsonData)
jsonFile.Close()
}
run the code above and you should be able to see a new Employees.json file appear in the same directory.
Employees.json
[
{
"ID": 101,
"FirstName": "Derek",
"LastName": "Young",
"UserName": "derekyoung"
},
{
"ID": 102,
"FirstName": "John",
"LastName": "Smith",
"UserName": "johnsmith"
}
]
Reference :
https://www.socketloop.com/tutorials/golang-convert-csv-data-to-json-format-and-save-to-file
See also : Read a XML file in Go
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
+15.7k Golang : Update database with GORM example
+10.8k Golang : Generate random elements without repetition or duplicate
+19.3k Golang : Example for DSA(Digital Signature Algorithm) package functions
+20.6k Golang : Underscore or snake_case to camel case example
+6.2k Golang : Selection sort example
+7.1k Golang : Example of custom handler for Gorilla's Path usage.
+16.6k Golang : Get own process identifier
+9k Golang : How to check if a string with spaces in between is numeric?
+5.8k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+12.4k Golang : Pass database connection to function called from another package and HTTP Handler
+5.2k Golang : Intercept, inject and replay HTTP traffics from web server
+20.9k Golang : Get password from console input without echo or masked