json2xml package - github.com/vinitkumar/json2xml-go - Go Packages

Package json2xml provides utilities to convert JSON data to XML format.

Package json2xml provides utilities to convert JSON data to XML format.

This package is a Go port of the Python json2xml library. It supports various conversion options including:

  • Custom root element names
  • Type attributes on elements
  • List item wrapping
  • CDATA sections
  • XML namespaces
  • XPath 3.1 json-to-xml format

Example usage:

data := map[string]any{"name": "John", "age": 30}
converter := json2xml.New(data)
xml, err := converter.ToXML()
if err != nil {
    log.Fatal(err)
}
fmt.Println(xml)
package main

import (
	"fmt"

	json2xml "github.com/vinitkumar/json2xml-go"
)

func main() {
	data := map[string]any{
		"name":   "John",
		"age":    30,
		"active": true,
	}

	converter := json2xml.New(data)
	xml, err := converter.WithPretty(false).WithAttrType(false).ToXMLString()
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(xml)
}
Output:
<?xml version="1.0" encoding="UTF-8" ?><all><active>true</active><age>30</age><name>John</name></all>
package main

import (
	"fmt"

	json2xml "github.com/vinitkumar/json2xml-go"
)

func main() {
	data := map[string]any{
		"colors": []any{"red", "green", "blue"},
	}

	xml, err := json2xml.New(data).
		WithPretty(false).
		WithAttrType(false).
		ToXMLString()
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(xml)
}
Output:
<?xml version="1.0" encoding="UTF-8" ?><all><colors><item>red</item><item>green</item><item>blue</item></colors></all>
package main

import (
	"fmt"

	json2xml "github.com/vinitkumar/json2xml-go"
)

func main() {
	data := map[string]any{
		"bike": []any{"blue", "green"},
	}

	xml, err := json2xml.New(data).
		WithPretty(false).
		WithAttrType(false).
		WithItemWrap(false).
		WithRoot(false).
		ToXMLString()
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(xml)
}
Output:
<bike>blue</bike><bike>green</bike>
package main

import (
	"fmt"

	json2xml "github.com/vinitkumar/json2xml-go"
)

func main() {
	jsonStr := `{"login":"mojombo","id":1}`
	data, err := json2xml.ReadFromString(jsonStr)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	xml, err := json2xml.New(data).
		WithPretty(false).
		WithAttrType(false).
		ToXMLString()
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(xml)
}
Output:
<?xml version="1.0" encoding="UTF-8" ?><all><id>1</id><login>mojombo</login></all>
package main

import (
	"fmt"

	json2xml "github.com/vinitkumar/json2xml-go"
)

func main() {
	data := map[string]any{"key": "value"}

	xml, err := json2xml.New(data).
		WithRoot(false).
		WithPretty(false).
		WithAttrType(false).
		ToXMLString()
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(xml)
}
Output:
<key>value</key>
package main

import (
	"fmt"

	json2xml "github.com/vinitkumar/json2xml-go"
)

func main() {
	data := map[string]any{"name": "Alice", "age": 25}

	xml, err := json2xml.New(data).
		WithXPathFormat(true).
		WithPretty(false).
		ToXMLString()
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(xml)
}
Output:
<?xml version="1.0" encoding="UTF-8" ?><map xmlns="http://www.w3.org/2005/xpath-functions"><number key="age">25</number><string key="name">Alice</string></map>

View Source

const (
	Version = "1.0.0"
	Author  = "Vinit Kumar"
	Email   = "mail@vinitkumar.me"
)

Version information

View Source

const XPathFunctionsNS = "http://www.w3.org/2005/xpath-functions"

XPathFunctionsNS is the XPath 3.1 json-to-xml namespace.

View Source

var (
	
	ErrJSONRead = errors.New("invalid JSON file")

	
	ErrInvalidData = errors.New("invalid data")

	
	ErrURLRead = errors.New("URL is not returning correct response")

	
	ErrStringRead = errors.New("input is not a proper JSON string")
)

Custom errors for json2xml package

Convert routes elements to the right function based on their data type.

ConvertBool converts a boolean into an XML element.

ConvertDict converts a map into an XML string.

ConvertKV converts a key-value pair into an XML element.

ConvertList converts a slice into an XML string.

ConvertNone converts a null value into an XML element.

ConvertToXML is a convenience function to convert JSON data to XML.

ConvertToXPath31 converts a value to XPath 3.1 json-to-xml format.

DefaultItemFunc returns "item" for any parent element.

Dict2XMLStr parses dict to XML string.

DictToXML converts a Go value into XML bytes.

EscapeXML escapes special XML characters in a string.

GetUniqueID generates a unique ID for a given element.

GetXMLType returns the XML type string for a given value.

GetXPath31TagName determines XPath 3.1 tag name by value type.

IsPrimitiveType checks if a value is a primitive type.

KeyIsValidXML checks if a key is a valid XML name.

List2XMLStr converts a list to XML string.

MakeAttrString creates a string of XML attributes from a map.

MakeID generates a random ID for a given element.

MakeValidXMLName tests an XML name and fixes it if invalid.

PrettyPrint formats XML with indentation.

ReadFromJSON reads a JSON file and returns the parsed data.

ReadFromString parses a JSON string and returns the data.

ReadFromURL loads JSON data from a URL and returns the parsed data.

WrapCDATA wraps a string in CDATA sections.

ItemFunc is a function that generates element names for list items.

JSON2xml is the main converter struct.

func New(data any) *JSON2xml

New creates a new JSON2xml converter with default options.

ToXML converts the data to XML. Returns the XML as a string when pretty=true, or as bytes when pretty=false. Returns nil if data is empty or nil.

ToXMLBytes converts the data to XML and returns it as bytes.

ToXMLString converts the data to XML and returns it as a string.

func (j *JSON2xml) WithAttrType(attrType bool) *JSON2xml

WithAttrType sets whether to include type attributes.

func (j *JSON2xml) WithItemWrap(itemWrap bool) *JSON2xml

WithItemWrap sets whether to wrap list items in <item> elements.

func (j *JSON2xml) WithPretty(pretty bool) *JSON2xml

WithPretty sets whether to pretty-print the output.

func (j *JSON2xml) WithRoot(root bool) *JSON2xml

WithRoot sets whether to include root element.

func (j *JSON2xml) WithWrapper(wrapper string) *JSON2xml

WithWrapper sets a custom wrapper element name.

func (j *JSON2xml) WithXPathFormat(xpathFormat bool) *JSON2xml

WithXPathFormat sets whether to use XPath 3.1 json-to-xml format.

Options configures the XML conversion behavior.

func DefaultOptions() Options

DefaultOptions returns the default conversion options.