see below my
main.go
type Data struct {
unit []string `json:"unit"`
}
func receive(w http.ResponseWriter, r *http.Request) {
dec := json.NewDecoder(r.Body)
for {
var d Data
if err := dec.Decode(&d); err == io.EOF {
break
} else if err != nil {
log.Println(err)
}
log.Printf("%s
", d.unit)
}
}
Error that is throwed: "json: cannot unmarshal array into GO value of type main.Data"
moj.js
$(function(){
$('#start').on('click', function(){
var i;
var j = 0;
for (i = 0; i < result.length; i++){
if(result[i] == null){
}else if(result[i]==""){
}else{
lookup[j] = result[i];
j++
}
}
$.ajax({
type: 'POST',
url: '/start',
data: '[{"unit":"'+lookup+'"}]',
dataType: "json",
contentType: "application/json",
success: function () {
alert("Data posted.")
},
error: function(){
alert('Error posting data.')
}
});
});
});
The "json" that I send looks like: [{"unit":"something"}].
In the console I can see the data has been posted like this.
Two things:
See: https://play.golang.org/p/4kfIQTXqYi
type Data struct {
Unit string `json:"unit"`
}
func receive(w http.ResponseWriter, r *http.Request) {
dec := json.NewDecoder(r.Body)
for {
var d []Data
if err := dec.Decode(&d); err == io.EOF {
break
} else if err != nil {
log.Println(err)
}
log.Printf("%s
", d.Unit)
}
}