Skip to content

XML to JSON converter written in Go (no schema, no structs)

License

Notifications You must be signed in to change notification settings

txix-open/goxml2json

 
 

Repository files navigation

goxml2json CircleCI

Go package that converts XML to JSON

Install

go get -u https://github.com/txix-open/goxml2json

Importing

import https://github.com/txix-open/goxml2json

Usage

Code example

  package main

import (
	"fmt"
	"strings"

	xj "github.com/basgys/goxml2json"
)

func main() {
	// xml is an io.Reader
	xml := strings.NewReader(`<?xml version="1.0" encoding="UTF-8"?><hello>world</hello>`)
	converter := xj.NewConverter(
		xj.WithAttrPrefix("-"),
	)
	json, err := converter.Convert(xml)
	if err != nil {
		panic("That's embarrassing...")
	}

	fmt.Println(json.String())
	// {"hello": ["world"]}
}

Input

  <?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="CGImap 0.0.2">
    <bounds minlat="54.0889580" minlon="12.2487570" maxlat="54.0913900" maxlon="12.2524800"/>
    <foo>bar</foo>
</osm>

Output

  {
  "osm": {
    "-version": 0.6,
    "-generator": "CGImap 0.0.2",
    "bounds": {
      "-minlat": "54.0889580",
      "-minlon": "12.2487570",
      "-maxlat": "54.0913900",
      "-maxlon": "12.2524800"
    },
    "foo": "bar"
  }
}

With type conversion

  package main

import (
	"fmt"
	"strings"

	xj "github.com/basgys/goxml2json"
)

func main() {
	// xml is an io.Reader
	xml := strings.NewReader(`<?xml version="1.0" encoding="UTF-8"?><price>19.95</price>`)
	converter := xj.NewConverter(
		xj.WithAttrPrefix("-"),
		xj.WithTypeConverter(xj.Float),
	)
	json, err := converter.Convert(xml)
	if err != nil {
		panic("That's embarrassing...")
	}

	fmt.Println(json.String())
	// {"price": [19.95]}
}

About

XML to JSON converter written in Go (no schema, no structs)

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Go 100.0%