-- 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"?>
<company>
        <person>
                <id>100987</id>
                <firstname>Cihan</firstname>
                <lastname>Özhan</lastname>
                <username>cihanozhan</username>
        </person>
        <person>
                <id>100995</id>
                <firstname>Kerim</firstname>
                <lastname>Fırat</lastname>
                <username>kerimfirat</username>
        </person>
        <person>
                <id>100985</id>
                <firstname>Emre</firstname>
                <lastname>Okumuş</lastname>
                <username>emreokumus</username>
        </person>
        <person>
                <id>100585</id>
                <firstname>Barış</firstname>
                <lastname>Özhan</lastname>
                <username>barisozhan</username>
        </person>
</company>

Go code for the project;

package main

import (
	"encoding/json"
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"os"
)

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)
		return
	}
	defer xmlFile.Close()

	xmlData, _ := ioutil.ReadAll(xmlFile)

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

	// Write XML on screen
	fmt.Println(c.Persons)

	// 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 {
		fmt.Println(err)
		os.Exit(1)
	}

	// Write JSON on screen
	fmt.Println(string(jsonData))

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

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

	jsonFile.Write(jsonData)
	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.

Output;

[
    {"ID":100987,"FirstName":"Cihan","LastName":"Özhan","UserName":"cihanozhan"},
    {"ID":100995,"FirstName":"Kerim","LastName":"Fırat","UserName":"kerimfirat"},
    {"ID":100985,"FirstName":"Emre","LastName":"Okumuş","UserName":"emreokumus"},
    {"ID":100585,"FirstName":"Barış","LastName":"Özhan","UserName":"barisozhan"}
]

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

Good work!
Cihan Özhan

Yorumla

Yorum