Categorygithub.com/andrewdavidburt/goxml2json-opensearch-empty-is-null
repositorypackage
0.0.0-20220909051715-2ae92426d14d
Repository: https://github.com/andrewdavidburt/goxml2json-opensearch-empty-is-null.git
Documentation: pkg.go.dev

# README

goxml2json CircleCI

Go package that converts XML to JSON

Fork

This fork is to help with data sent opensearch, setting empty fields to null rather than "". 
"" is always interpreted as a string, which can create conflicts when the field should be a 
nested object. null is interpreted neutrally for both strings/values and objects, and creates 
no conflicts. 

Install

go get -u github.com/basgys/goxml2json

Importing

import github.com/basgys/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>`)
  	json, err := xj.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>`)
  	json, err := xj.Convert(xml, xj.WithTypeConverter(xj.Float))
  	if err != nil {
  		panic("That's embarrassing...")
  	}

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

With empty value setting

  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"?><something></something>`)
  	json, err := xj.Convert(xml, xj.EmptySet("null"))
  	if err != nil {
  		panic("That's embarrassing...")
  	}

  	fmt.Println(json.String())
  	// {"price": null}
  }

Contributing

Feel free to contribute to this project if you want to fix/extend/improve it.

Contributors

TODO

  • Categorise errors
  • Option to prettify the JSON output
  • Benchmark