json2xml

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 27, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

README

json2xml hero

json2xml-go

A Go port of the Python json2xml library for converting JSON data to XML format.

Go Reference Go Report Card

Features

  • Convert JSON/Go maps to XML
  • Customizable root element names
  • Optional type attributes on elements
  • List item wrapping control
  • CDATA sections support
  • XML namespaces support
  • XPath 3.1 json-to-xml format support
  • Pretty printing with indentation
  • Command-line tool for easy conversion

Requirements

  • Go 1.26.5 or newer

Installation

As a Library
go get github.com/vinitkumar/json2xml-go
As a CLI Tool

Quick install (binary only):

go install github.com/vinitkumar/json2xml-go/cmd/json2xml-go@latest

Full install with man page:

# Clone the repository
git clone https://github.com/vinitkumar/json2xml-go.git
cd json2xml-go

# Install binary and man page (may need sudo for /usr/local)
sudo make install

# Or install to a custom location (no sudo needed)
make PREFIX=~/.local install

After installation, you can access the man page:

man json2xml-go

Uninstall:

sudo make uninstall
# Or if installed to custom location:
make PREFIX=~/.local uninstall

CLI Usage

The json2xml-go command-line tool provides an easy way to convert JSON to XML from the terminal.

Basic Examples
# Convert a JSON file to XML
json2xml-go data.json

# Convert with custom wrapper element
json2xml-go -w root data.json

# Read JSON from string
json2xml-go -s '{"name": "John", "age": 30}'

# Read from stdin
cat data.json | json2xml-go -

# Output to file
json2xml-go -o output.xml data.json

# Use XPath 3.1 format
json2xml-go -x data.json

# Disable pretty printing and type attributes
json2xml-go -p=false -t=false data.json

# Without item wrapping for lists
json2xml-go -i=false data.json
CLI Options
Input Options:
  -u, --url string        Read JSON from URL
  -s, --string string     Read JSON from string
  [input-file]            Read JSON from file (use - for stdin)

Output Options:
  -o, --output string     Output file (default: stdout)

Conversion Options:
  -w, --wrapper string    Wrapper element name (default "all")
  -r, --root              Include root element (default true)
  -p, --pretty            Pretty print output (default true)
  -t, --type              Include type attributes (default true)
  -i, --item-wrap         Wrap list items in <item> elements (default true)
  -x, --xpath             Use XPath 3.1 json-to-xml format
  -c, --cdata             Wrap string values in CDATA sections
  -l, --list-headers      Repeat headers for each list item

Other Options:
  -v, --version           Show version information
  -h, --help              Show help message

Library Usage

Basic Usage
package main

import (
    "fmt"
    "log"

    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.ToXMLString()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(xml)
}

Output:

<?xml version="1.0" encoding="UTF-8"?>
<all>
  <active type="bool">true</active>
  <age type="int">30</age>
  <name type="str">John</name>
</all>
Reading from JSON File
data, err := json2xml.ReadFromJSON("data.json")
if err != nil {
    log.Fatal(err)
}

xml, err := json2xml.New(data).ToXMLString()
Reading from JSON String
jsonStr := `{"login":"mojombo","id":1}`
data, err := json2xml.ReadFromString(jsonStr)
if err != nil {
    log.Fatal(err)
}

xml, err := json2xml.New(data).ToXMLString()
Reading from a URL

Remote reads allow only credential-free HTTP(S) URLs resolving to public addresses and limit decoded responses to 10 MiB by default:

data, err := json2xml.ReadFromURL("https://api.example.com/data.json", nil)

Trusted callers can explicitly permit private-network URLs or choose a smaller response limit:

data, err := json2xml.ReadFromURL(
    "http://127.0.0.1:8080/data.json",
    nil,
    json2xml.URLReadOptions{
        AllowPrivateNetworks: true,
        MaxResponseBytes:     1 << 20,
    },
)
Customization Options
data := map[string]any{"key": "value"}

xml, err := json2xml.New(data).
    WithWrapper("root").       // Custom wrapper element name
    WithRoot(true).            // Include root element
    WithPretty(true).          // Pretty print output
    WithAttrType(true).        // Include type attributes
    WithItemWrap(true).        // Wrap list items in <item> elements
    WithXPathFormat(false).    // Use XPath 3.1 format
    ToXMLString()
Without Item Wrapping
data := map[string]any{"colors": []any{"red", "green", "blue"}}

// With ItemWrap = true (default):
// <colors><item>red</item><item>green</item><item>blue</item></colors>

// With ItemWrap = false:
// <colors>red</colors><colors>green</colors><colors>blue</colors>

xml, err := json2xml.New(data).
    WithItemWrap(false).
    WithAttrType(false).
    ToXMLString()
XPath 3.1 Format

The library supports XPath 3.1 json-to-xml format:

data := map[string]any{"name": "John", "age": 30}

xml, err := json2xml.New(data).
    WithXPathFormat(true).
    WithPretty(false).
    ToXMLString()

Output:

<?xml version="1.0" encoding="UTF-8" ?><map xmlns="http://www.w3.org/2005/xpath-functions"><number key="age">30</number><string key="name">John</string></map>
Using DictToXML Directly

For more control, you can use the DictToXML function directly:

data := map[string]any{"key": "value"}
opts := json2xml.DefaultOptions()
opts.CustomRoot = "myroot"
opts.AttrType = false

xmlBytes := json2xml.DictToXML(data, opts)
XML Namespaces
data := map[string]any{"ns1:node1": "data in namespace 1"}
opts := json2xml.DefaultOptions()
opts.XMLNamespaces = map[string]any{
    "ns1": "https://example.com/ns1",
    "xmlns": "http://example.com/default",
}

xmlBytes := json2xml.DictToXML(data, opts)

API Reference

Types
JSON2xml

Main converter struct with fluent API:

  • New(data any) *JSON2xml - Create new converter
  • WithWrapper(name string) - Set wrapper element name (default: "all")
  • WithRoot(bool) - Include root element (default: true)
  • WithPretty(bool) - Pretty print output (default: true)
  • WithAttrType(bool) - Include type attributes (default: true)
  • WithItemWrap(bool) - Wrap list items (default: true)
  • WithXPathFormat(bool) - Use XPath 3.1 format (default: false)
  • ToXML() (any, error) - Convert to XML
  • ToXMLString() (string, error) - Convert to XML string
  • ToXMLBytes() ([]byte, error) - Convert to XML bytes
Options

Configuration struct for DictToXML:

type Options struct {
    Root          bool              // Wrap in root element
    CustomRoot    string            // Root element name
    IDs           bool              // Add unique IDs
    AttrType      bool              // Add type attributes
    ItemWrap      bool              // Wrap list items
    ItemFunc      ItemFunc          // Custom item name function
    CDATA         bool              // Wrap strings in CDATA
    XMLNamespaces map[string]any    // XML namespaces
    ListHeaders   bool              // Repeat headers for list items
    XPathFormat   bool              // XPath 3.1 format
}
URLReadOptions

Security controls for URL reads:

type URLReadOptions struct {
    AllowPrivateNetworks bool  // Permit trusted private and loopback targets
    MaxResponseBytes     int64 // Decoded response limit; zero uses 10 MiB
}
Functions
  • ReadFromJSON(filename string) (any, error) - Read JSON file
  • ReadFromString(jsonData string) (any, error) - Parse JSON string
  • ReadFromURL(url string, params map[string]string, options ...URLReadOptions) (any, error) - Fetch bounded JSON from a public URL
  • DictToXML(obj any, opts Options) []byte - Convert to XML bytes
  • ConvertToXML(data any, opts *Options) ([]byte, error) - Convenience function
Errors
  • ErrJSONRead - Error reading JSON file
  • ErrInvalidData - Invalid data error
  • ErrURLRead - Error reading from URL
  • ErrStringRead - Error parsing JSON string

Performance Benchmarks

Comprehensive benchmarks comparing Python, Go, and Zig implementations:

Test Case Python (CPython) Go Zig
Small JSON (47 bytes) 68.88ms 7.13ms 2.65ms
Medium JSON (2.6 KB) 73.40ms 4.85ms 2.13ms
Large JSON (323 KB) 420.06ms 68.88ms 5.90ms
Very Large JSON (1.6 MB) 2.08s 288.75ms 20.62ms

Summary: Go is 7x faster than Python on average.

Recommendation by Use Case:

Use Case Recommended
CLI tool for small/medium files Go (this library)
High-throughput batch processing Go or Zig
Integration with Python codebase Python (json2xml)
Maximum performance Zig (json2xml-zig)

For detailed benchmarks, see BENCHMARKS.md.

Releases

See CHANGELOG.md for release notes and upgrade information.

This library is part of the json2xml family:

  • Python: json2xml - The original implementation, best for Python integration
  • Zig: json2xml-zig - 12x faster than Go, for maximum performance
Python Version

This is a Go port of the original Python json2xml library. If you prefer Python, you can install it via pip:

pip install json2xml

The Python version includes the same features and a CLI tool (json2xml-py).

License

MIT License - same as the original Python library.

Author

Vinit Kumar [email protected]

Documentation

Overview

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)
Example
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>
Example (ListConversion)
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>
Example (NoItemWrap)
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>
Example (ReadFromString)
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>
Example (WithoutRoot)
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>
Example (XpathFormat)
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>

Index

Examples

Constants

View Source
const (
	Version = "1.0.0"
	Author  = "Vinit Kumar"
	Email   = "[email protected]"
)

Version information

View Source
const DefaultMaxResponseBytes int64 = 10 << 20
View Source
const XPathFunctionsNS = "http://www.w3.org/2005/xpath-functions"

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

Variables

View Source
var (
	// ErrJSONRead is returned when there is an error reading JSON data.
	ErrJSONRead = errors.New("invalid JSON file")

	// ErrInvalidData is returned when the data is invalid.
	ErrInvalidData = errors.New("invalid data")

	// ErrURLRead is returned when there is an error reading from a URL.
	ErrURLRead = errors.New("URL is not returning correct response")

	// ErrStringRead is returned when there is an error reading from a string.
	ErrStringRead = errors.New("input is not a proper JSON string")
)

Custom errors for json2xml package

Functions

func Convert

func Convert(obj any, opts Options, parent string) string

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

func ConvertBool

func ConvertBool(key string, val bool, attrType bool, attrs map[string]any, cdata bool) string

ConvertBool converts a boolean into an XML element.

func ConvertDict

func ConvertDict(obj map[string]any, opts Options, parent string) string

ConvertDict converts a map into an XML string.

func ConvertKV

func ConvertKV(key string, val any, attrType bool, attrs map[string]any, cdata bool) string

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

func ConvertList

func ConvertList(items []any, opts Options, parent string) string

ConvertList converts a slice into an XML string.

func ConvertNone

func ConvertNone(key string, attrType bool, attrs map[string]any, cdata bool) string

ConvertNone converts a null value into an XML element.

func ConvertToXML

func ConvertToXML(data any, opts *Options) ([]byte, error)

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

func ConvertToXPath31

func ConvertToXPath31(obj any, parentKey string) string

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

func DefaultItemFunc

func DefaultItemFunc(parent string) string

DefaultItemFunc returns "item" for any parent element.

func Dict2XMLStr

func Dict2XMLStr(opts Options, attrs map[string]any, item map[string]any, itemName string, parentIsList bool, parent string) string

Dict2XMLStr parses dict to XML string.

func DictToXML

func DictToXML(obj any, opts Options) []byte

DictToXML converts a Go value into XML bytes.

func EscapeXML

func EscapeXML(s string) string

EscapeXML escapes special XML characters in a string.

func GetUniqueID

func GetUniqueID(element string) string

GetUniqueID generates a unique ID for a given element.

func GetXMLType

func GetXMLType(val any) string

GetXMLType returns the XML type string for a given value.

func GetXPath31TagName

func GetXPath31TagName(val any) string

GetXPath31TagName determines XPath 3.1 tag name by value type.

func IsPrimitiveType

func IsPrimitiveType(val any) bool

IsPrimitiveType checks if a value is a primitive type.

func KeyIsValidXML

func KeyIsValidXML(key string) bool

KeyIsValidXML checks if a key is a valid XML name.

func List2XMLStr

func List2XMLStr(opts Options, attrs map[string]any, items []any, itemName string) string

List2XMLStr converts a list to XML string.

func MakeAttrString

func MakeAttrString(attrs map[string]any) string

MakeAttrString creates a string of XML attributes from a map.

func MakeID

func MakeID(element string, start, end int) string

MakeID generates a random ID for a given element.

func MakeValidXMLName

func MakeValidXMLName(key string, attrs map[string]any) (string, map[string]any)

MakeValidXMLName tests an XML name and fixes it if invalid.

func PrettyPrint

func PrettyPrint(xmlBytes []byte) (string, error)

PrettyPrint formats XML with indentation.

func ReadFromJSON

func ReadFromJSON(filename string) (any, error)

ReadFromJSON reads a JSON file and returns the parsed data.

func ReadFromString

func ReadFromString(jsonData string) (any, error)

ReadFromString parses a JSON string and returns the data.

func ReadFromURL

func ReadFromURL(address string, params map[string]string, suppliedOptions ...URLReadOptions) (any, error)

ReadFromURL loads JSON data from a URL and returns the parsed data. By default, only credential-free HTTP(S) URLs resolving to public addresses are allowed and decoded responses are limited to DefaultMaxResponseBytes.

func WrapCDATA

func WrapCDATA(s string) string

WrapCDATA wraps a string in CDATA sections.

Types

type ItemFunc

type ItemFunc func(parent string) string

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

type JSON2xml

type JSON2xml struct {
	// contains filtered or unexported fields
}

JSON2xml is the main converter struct.

func New

func New(data any) *JSON2xml

New creates a new JSON2xml converter with default options.

func (*JSON2xml) ToXML

func (j *JSON2xml) ToXML() (any, error)

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

func (*JSON2xml) ToXMLBytes

func (j *JSON2xml) ToXMLBytes() ([]byte, error)

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

func (*JSON2xml) ToXMLString

func (j *JSON2xml) ToXMLString() (string, error)

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

func (*JSON2xml) WithAttrType

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

WithAttrType sets whether to include type attributes.

func (*JSON2xml) WithCDATA

func (j *JSON2xml) WithCDATA(cdata bool) *JSON2xml

WithCDATA sets whether to wrap string values in CDATA sections.

func (*JSON2xml) WithItemWrap

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

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

func (*JSON2xml) WithListHeaders

func (j *JSON2xml) WithListHeaders(listHeaders bool) *JSON2xml

WithListHeaders sets whether to repeat headers for each list item.

func (*JSON2xml) WithPretty

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

WithPretty sets whether to pretty-print the output.

func (*JSON2xml) WithRoot

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

WithRoot sets whether to include root element.

func (*JSON2xml) WithWrapper

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

WithWrapper sets a custom wrapper element name.

func (*JSON2xml) WithXPathFormat

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

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

type Options

type Options struct {
	// Root specifies whether to wrap output in an XML root element.
	Root bool
	// CustomRoot specifies the name of the root element.
	CustomRoot string
	// IDs specifies whether elements get unique IDs.
	IDs bool
	// AttrType specifies whether elements get a data type attribute.
	AttrType bool
	// ItemWrap specifies whether to wrap list items in <item> elements.
	ItemWrap bool
	// ItemFunc generates element names for list items.
	ItemFunc ItemFunc
	// CDATA specifies whether string values should be wrapped in CDATA sections.
	CDATA bool
	// XMLNamespaces is a map of namespace prefixes to URIs.
	XMLNamespaces map[string]any
	// ListHeaders specifies whether to repeat headers for each list item.
	ListHeaders bool
	// XPathFormat specifies whether to use XPath 3.1 json-to-xml format.
	XPathFormat bool
}

Options configures the XML conversion behavior.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns the default conversion options.

type URLReadOptions

type URLReadOptions struct {
	// AllowPrivateNetworks permits loopback, private, link-local, and other
	// non-public destinations. It should only be enabled for trusted URLs.
	AllowPrivateNetworks bool
	// MaxResponseBytes limits the decoded response body. Zero uses
	// DefaultMaxResponseBytes.
	MaxResponseBytes int64
}

URLReadOptions controls the security boundaries applied to remote JSON reads.

Directories

Path Synopsis
cmd
json2xml-go command
json2xml-go is a command-line tool to convert JSON data to XML format.
json2xml-go is a command-line tool to convert JSON data to XML format.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL