-- Go

Converting XML Data to JSON with Go

Converting XML Data to JSON with Go

Along with evolving software technologies, data formats and transfer methods have evolved in many different ways. For many years, the most widely used common data transfer format was XML. However, many problems with this language cannot be ignored. If we think simple; why do we take up extra space in the disk with unnecessary XML tags? That’s why JSON was developed as a lighter data format. And this file format has been widely used for years. In this example, we will examine how to convert an XML data into JSON format.

We need an XML dataset to convert to JSON. Our sample XML will look like this:

The name of the XML file; Employees.xml

<?xml version="1.0"?>

Go code for the project;

package main

import (

type jsonPerson struct {
	ID        int
	FirstName string
	LastName  string
	UserName  string

type Person struct {
	XMLName   xml.Name `xml:"person"`
	ID        int      `xml:"id"`
	FirstName string   `xml:"firstname"`
	LastName  string   `xml:"lastname"`
	UserName  string   `xml:"username"`

type Company struct {
	XMLName xml.Name `xml:"company"`
	Persons []Person `xml:"person"`

// Function of object Person
func (p Person) String() string {
	return fmt.Sprintf("\t ID : %d - FirstName : %s - LastName : %s - UserName : %s \n", p.ID, p.FirstName, p.LastName, p.UserName)

func main() {
	xmlFile, err := os.Open("Employees.xml")
	if err != nil {
		fmt.Println("Opening file error : ", err)
	defer xmlFile.Close()

	xmlData, _ := ioutil.ReadAll(xmlFile)

	var c Company
	xml.Unmarshal(xmlData, &c)

	// Write XML on screen

	// Convert to JSON
	var person jsonPerson
	var persons []jsonPerson

	for _, value := range c.Persons {
		person.ID = value.ID
		person.FirstName = value.FirstName
		person.LastName = value.LastName
		person.UserName = value.UserName

		persons = append(persons, person)

	jsonData, err := json.Marshal(persons)

	if err != nil {

	// Write JSON on screen

	// Write to JSON file
	jsonFile, err := os.Create("./Employees.json")

	if err != nil {
	defer jsonFile.Close()


When you run the program, a file named Employees.json will be created in the folder where the project is located. So we created the JSON version of the Employees.xml file.



Github; https://github.com/cihanozhan/golang-json-samples

Good work!
Cihan Özhan