It's not a matter of marshal or unmarshal, it's what do I need to write to my writer in combination with my Jquery?
Right now I have this for Go
func serveJson(w http.ResponseWriter, r *http.Request, ps httprouter.Params){
j, _ := os.Open("adjs.json")
defer j.Close()
var obj respWords
json.NewDecoder(j).Decode(&obj)
js, _ := json.Marshal(obj)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
and this is my jquery getting the json
<script type = "text/javascript">
function randomize() {
scene = {}
$.getJSON('adjs.json', function(scene){
console.log('encoding')
})
console.log(scene)
}
</script>
your async request does not save the data to the external variable, do your logic in the success function of your ajax request
$.getJSON('adjs.json', function(scene){
console.log(scene);
//do logic here with scene
});
You can serve a file containing JSON as follows:
func serveJson(w http.ResponseWriter, r *http.Request, ps httprouter.Params){
j, err := os.Open("adjs.json")
if err != nil {
http.Error(w, "Internal Server Error", 500)
return
}
defer j.Close(0
w.Header().Set("Content-Type", "application/json")
io.Copy(w, f)
}
There's no need to decode and encode the file.
You can also use ServeFile:
func serveJson(w http.ResponseWriter, r *http.Request, ps httprouter.Params){
http.ServeFile(w, r, "adjs.json")
}