How to Convert XML to JSON in Golang

1. Introduction

XML (eXtensible Markup Language) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. JSON (JavaScript Object Notation), on the other hand, is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.

Go's standard library provides packages to decode XML and encode JSON. This blog post demonstrates how to convert XML to JSON in Go.

2. Program Steps

1. Define types that match the XML structure.

2. Decode the XML into the Go types using encoding/xml.

3. Encode the resulting Go types into JSON using encoding/json.

4. Handle any errors that occur during decoding and encoding.

5. Output the JSON equivalent of the XML.

3. Code Program

package main

import (
	"encoding/json"
	"encoding/xml"
	"fmt"
	"log"
)

// Define XML and JSON types
type Person struct {
	XMLName   xml.Name `xml:"person"`
	FirstName string   `xml:"firstName" json:"first_name"`
	LastName  string   `xml:"lastName" json:"last_name"`
}

func main() {
	// XML data
	xmlData := `<person><firstName>John</firstName><lastName>Doe</lastName></person>`

	// Step 1: Decode XML data
	var person Person
	err := xml.Unmarshal([]byte(xmlData), &person)
	if err != nil {
		// Step 2: Handle errors in XML decoding
		log.Fatalf("Error unmarshaling XML: %s", err)
	}

	// Step 3: Encode to JSON
	jsonData, err := json.Marshal(person)
	if err != nil {
		// Step 4: Handle errors in JSON encoding
		log.Fatalf("Error marshaling to JSON: %s", err)
	}

	// Step 5: Output the JSON
	fmt.Println("JSON output:", string(jsonData))
}

Output:

JSON output: {"first_name":"John","last_name":"Doe"}

Explanation:

1. package main - The package declaration for the Go program.

2. import statements - Importing fmt for printing, log for logging errors, encoding/xml for XML decoding, and encoding/json for JSON encoding.

3. The Person type is defined with tags for both XML and JSON to allow proper decoding and encoding, respectively.

4. xmlData is a string literal containing XML data representing a person.

5. xml.Unmarshal is used to decode the XML data into a Person object.

6. If there's an error during XML decoding, it will be logged, and the program will exit.

7. json.Marshal is then used to encode the Person object into JSON format.

8. If there's an error during JSON encoding, it will also be logged, and the program will exit.

9. The resulting JSON string is printed to the console.

10. The output shows the JSON representation of the original XML data.


Comments