How to Convert a JSON Object to XML using Go
When converting between JSON and other common data types, we can do so by using either a JSON file or object as input. In this article, I’ll demonstrate a quick & easy way to perform the latter operation with zero hassle. This method simply calls the Cloudmersive JSON Object to XML Conversion API; all you’ll need to do is use the code examples provided in below to structure your API call, and then register a free account on our website to get a Cloudmersive API key (free accounts provide a limit of 800 API calls per month with zero additional commitments).
To call the API, all we need to do is copy & paste the below code into our file, and then include our JSON object & API key in the appropriate fields:
package mainimport (
"fmt"
"strings"
"net/http"
"io/ioutil"
)func main() {url := "https://api.cloudmersive.com/convert/json/to/xml"
method := "POST"payload := strings.NewReader("0=%3C&1=o&2=b&3=j&4=e&5=c&6=t&7=%3E")client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Apikey", "YOUR-API-KEY-HERE")res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}
After that, we’re all done — no more code or configuration required!