How to Convert XML to JSON Format using Go
Converting between common data formats is a run-of-the-mill, day-to-day task for developers; as such, making those conversions shouldn’t take more than a second thought. With our XML to JSON conversion API, you can build one essential data format conversion service into your application and put your future data conversion needs to rest. All you need to do is register a free account on our website (free accounts supply a hard limit of 800 API calls per month with zero additional financial commitments) and use the ready-to-run Go code examples provided below to structure your API call.
To call the API, simply copy & paste the below code examples into your file (including your API key and input XML file in their respective fields), and you’re all done:
package mainimport (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)func main() {url := "https://api.cloudmersive.com/convert/xml/to/json"
method := "POST"payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
file, errFile1 := os.Open("/path/to/file")
defer file.Close()
part1,
errFile1 := writer.CreateFormFile("inputFile",filepath.Base("/path/to/file"))
_, errFile1 = io.Copy(part1, file)
if errFile1 != nil {
fmt.Println(errFile1)
return
}
err := writer.Close()
if err != nil {
fmt.Println(err)
return
}client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "multipart/form-data")
req.Header.Add("Apikey", "YOUR-API-KEY-HERE")req.Header.Set("Content-Type", writer.FormDataContentType())
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))
}
The output from this operation will include the encoding for a new JSON file. Simple as that!