-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathjsontoxml.go
57 lines (41 loc) · 890 Bytes
/
jsontoxml.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"github.com/clbanning/mxj"
)
func main() {
var inputData []byte
if len(os.Args) > 1 {
inputData = []byte(os.Args[1])
} else {
inputData, _ = ioutil.ReadAll(os.Stdin)
}
if len(inputData) > 0 {
xmlout, err := convertJSONToXML(inputData)
if err != nil {
log.Println(err.Error())
os.Exit(1)
}
fmt.Println(string(xmlout))
os.Exit(0)
} else {
os.Exit(1)
}
}
func convertJSONToXML(inputData []byte) (xmlout []byte, err error) {
var parsedJSON interface{}
if err := json.Unmarshal(inputData, &parsedJSON); err != nil {
return []byte(""), fmt.Errorf("invalid JSON found %s\n", inputData)
}
mxj.XMLEscapeChars(true)
xmlout, err2 := mxj.AnyXml(parsedJSON, "root")
if err2 != nil {
return []byte(""), errors.New("Error converting to XML")
}
return xmlout, nil
}