英文:
Unmarshal json to a array from post request
问题
请看下面的翻译结果:
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\n", d.unit)
}
}
抛出的错误信息为:"json: 无法将数组解组为 main.Data 类型的 GO 值"
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("数据已提交。")
},
error: function(){
alert('提交数据时出错。')
}
});
});
});
我发送的 "json" 数据看起来像这样:[{"unit":"something"}]。
在控制台中,我可以看到数据已经以这种方式被提交。
英文:
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\n", 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.
答案1
得分: 2
两件事情:
- 你正在解组一个 Data 切片,而不是一个 'unit' 切片。
- 将 'unit' 字段设为公开,以便通过反射对解码器可见。
参考: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\n", d.Unit)
}
}
英文:
Two things:
- You are unmarshalling a slice of Data rather than a slice of 'unit'.
- Make the 'unit' field public so that it is visible by reflection to the Decoder
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\n", d.Unit)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论