Skip to content

Instantly share code, notes, and snippets.

@noynaert
Created May 4, 2016 05:09
Show Gist options
  • Save noynaert/34c204801ac0509fc700d4f0c33f7736 to your computer and use it in GitHub Desktop.
Save noynaert/34c204801ac0509fc700d4f0c33f7736 to your computer and use it in GitHub Desktop.
This is an improved method of moving data from XML to JSON (or JSON to XML). Only one struct is needed, and you don't need to export to another struct. See the opening comment
package main
//
// This is a bit of an improvement over the code I did in class.
// There are two changes that might make your life easier
// 1) You can just use "string" instead of the XML data type.
// 2) You can include both the xml and json in the same backtick.
// All you have to do is put in a comma, like this:
// TypeOfError string `xml:"type,json:"type"
//
// The really nice thing about 2) is that you can use just one
// struct for both xml and json. There isn't a need to transfer
// each field over one at a time. Just unmarshal the data
// into the struct, and then marshallWithIndent it into the other
// format directly from the struct.
import (
"fmt"
"net/url"
"encoding/xml"
"net/http"
"log"
"io/ioutil"
"encoding/json"
)
type reportType struct{
Version string `xml:"version"`
TermsOfService string `xml:"termsofService"`
Problem myErrorType `xml:"error"`
}
type myErrorType struct{
TypeOfError string `xml:"type,json:"type"`
Desciption xml.CharData `xml:"description"`
}
func main() {
fmt.Println("data is from WeatherUnderground.")
fmt.Println("https://www.wunderground.com/")
var state, city string
state="MO"
city="Saint_Joseph"
baseURL := "http://api.wunderground.com/api/";
apiKey := "734951781f4140d6"
var query string
//set up the query
query = baseURL+apiKey +
"/conditions/q/"+
url.QueryEscape(state)+ "/"+
url.QueryEscape(city)+ ".xml"
fmt.Println("The escaped query: "+query)
response, err := http.Get(query)
doErr(err, "After the GET")
var body []byte
body, err = ioutil.ReadAll(response.Body)
doErr(err, "After Readall")
fmt.Println(body);
fmt.Printf("The body: %s\n",body)
//Unmarshalling
var report reportType
xml.Unmarshal(body, &report)
fmt.Printf("The Report: %s\n", report)
fmt.Printf("The description is [%s]\n",report.Problem.Desciption)
//Now marshal the data out in JSON
var data []byte
var output reportType
//output.Version = string(report.Version);
//report.Version -> output.Version
//output.TermsOfService = string(report.TermsOfService)
data,err = json.MarshalIndent(output,""," ")
doErr(err, "From marshalIndent")
fmt.Printf("JSON output nicely formatted: \n%s\n",data)
}
func doErr( err error, message string){
if err != nil{
log.Panicf("ERROR: %s %s \n", message, err.Error())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment