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>
- Constants
- Variables
- func Convert(obj any, opts Options, parent string) string
- func ConvertBool(key string, val bool, attrType bool, attrs map[string]any, cdata bool) string
- func ConvertDict(obj map[string]any, opts Options, parent string) string
- func ConvertKV(key string, val any, attrType bool, attrs map[string]any, cdata bool) string
- func ConvertList(items []any, opts Options, parent string) string
- func ConvertNone(key string, attrType bool, attrs map[string]any, cdata bool) string
- func ConvertToXML(data any, opts *Options) ([]byte, error)
- func ConvertToXPath31(obj any, parentKey string) string
- func DefaultItemFunc(parent string) string
- func Dict2XMLStr(opts Options, attrs map[string]any, item map[string]any, itemName string, ...) string
- func DictToXML(obj any, opts Options) []byte
- func EscapeXML(s string) string
- func GetUniqueID(element string) string
- func GetXMLType(val any) string
- func GetXPath31TagName(val any) string
- func IsPrimitiveType(val any) bool
- func KeyIsValidXML(key string) bool
- func List2XMLStr(opts Options, attrs map[string]any, items []any, itemName string) string
- func MakeAttrString(attrs map[string]any) string
- func MakeID(element string, start, end int) string
- func MakeValidXMLName(key string, attrs map[string]any) (string, map[string]any)
- func PrettyPrint(xmlBytes []byte) (string, error)
- func ReadFromJSON(filename string) (any, error)
- func ReadFromString(jsonData string) (any, error)
- func ReadFromURL(url string, params map[string]string) (any, error)
- func WrapCDATA(s string) string
- type ItemFunc
- type JSON2xml
- func (j *JSON2xml) ToXML() (any, error)
- func (j *JSON2xml) ToXMLBytes() ([]byte, error)
- func (j *JSON2xml) ToXMLString() (string, error)
- func (j *JSON2xml) WithAttrType(attrType bool) *JSON2xml
- func (j *JSON2xml) WithItemWrap(itemWrap bool) *JSON2xml
- func (j *JSON2xml) WithPretty(pretty bool) *JSON2xml
- func (j *JSON2xml) WithRoot(root bool) *JSON2xml
- func (j *JSON2xml) WithWrapper(wrapper string) *JSON2xml
- func (j *JSON2xml) WithXPathFormat(xpathFormat bool) *JSON2xml
- type Options
const ( Version = "1.0.0" Author = "Vinit Kumar" Email = "mail@vinitkumar.me" )
Version information
const XPathFunctionsNS = "http://www.w3.org/2005/xpath-functions"
XPathFunctionsNS is the XPath 3.1 json-to-xml namespace.
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.
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.
WithAttrType sets whether to include type attributes.
WithItemWrap sets whether to wrap list items in <item> elements.
WithPretty sets whether to pretty-print the output.
WithWrapper sets a custom wrapper element name.
Options configures the XML conversion behavior.
func DefaultOptions() Options
DefaultOptions returns the default conversion options.