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 ¶
- 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(address string, params map[string]string, suppliedOptions ...URLReadOptions) (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) WithCDATA(cdata bool) *JSON2xml
- func (j *JSON2xml) WithItemWrap(itemWrap bool) *JSON2xml
- func (j *JSON2xml) WithListHeaders(listHeaders 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
- type URLReadOptions
Examples ¶
Constants ¶
const ( Version = "1.0.0" Author = "Vinit Kumar" Email = "[email protected]" )
Version information
const DefaultMaxResponseBytes int64 = 10 << 20
const XPathFunctionsNS = "http://www.w3.org/2005/xpath-functions"
XPathFunctionsNS is the XPath 3.1 json-to-xml namespace.
Variables ¶
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 ConvertBool ¶
ConvertBool converts a boolean into an XML element.
func ConvertDict ¶
ConvertDict converts a map into an XML string.
func ConvertList ¶
ConvertList converts a slice into an XML string.
func ConvertNone ¶
ConvertNone converts a null value into an XML element.
func ConvertToXML ¶
ConvertToXML is a convenience function to convert JSON data to XML.
func ConvertToXPath31 ¶
ConvertToXPath31 converts a value to XPath 3.1 json-to-xml format.
func DefaultItemFunc ¶
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 GetUniqueID ¶
GetUniqueID generates a unique ID for a given element.
func GetXMLType ¶
GetXMLType returns the XML type string for a given value.
func GetXPath31TagName ¶
GetXPath31TagName determines XPath 3.1 tag name by value type.
func IsPrimitiveType ¶
IsPrimitiveType checks if a value is a primitive type.
func KeyIsValidXML ¶
KeyIsValidXML checks if a key is a valid XML name.
func List2XMLStr ¶
List2XMLStr converts a list to XML string.
func MakeAttrString ¶
MakeAttrString creates a string of XML attributes from a map.
func MakeValidXMLName ¶
MakeValidXMLName tests an XML name and fixes it if invalid.
func PrettyPrint ¶
PrettyPrint formats XML with indentation.
func ReadFromJSON ¶
ReadFromJSON reads a JSON file and returns the parsed data.
func ReadFromString ¶
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.
Types ¶
type JSON2xml ¶
type JSON2xml struct {
// contains filtered or unexported fields
}
JSON2xml is the main converter struct.
func (*JSON2xml) ToXML ¶
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 ¶
ToXMLBytes converts the data to XML and returns it as bytes.
func (*JSON2xml) ToXMLString ¶
ToXMLString converts the data to XML and returns it as a string.
func (*JSON2xml) WithAttrType ¶
WithAttrType sets whether to include type attributes.
func (*JSON2xml) WithItemWrap ¶
WithItemWrap sets whether to wrap list items in <item> elements.
func (*JSON2xml) WithListHeaders ¶
WithListHeaders sets whether to repeat headers for each list item.
func (*JSON2xml) WithPretty ¶
WithPretty sets whether to pretty-print the output.
func (*JSON2xml) WithWrapper ¶
WithWrapper sets a custom wrapper element name.
func (*JSON2xml) WithXPathFormat ¶
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. |
