将JSON从POST请求解析为数组。

huangapple go评论70阅读模式
英文:

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:&quot;unit&quot;`
     }
 func receive(w http.ResponseWriter, r *http.Request) {

  dec := json.NewDecoder(r.Body)
  for {
	var d Data
	if err := dec.Decode(&amp;d); err == io.EOF {
		break
	} else if err != nil {
		log.Println(err)
	}
	log.Printf(&quot;%s\n&quot;, d.unit)
  }
}

Error that is throwed: "json: cannot unmarshal array into GO value of type main.Data"

moj.js

 $(function(){
 $(&#39;#start&#39;).on(&#39;click&#39;, function(){
 var i;
 var j = 0;

 for (i = 0; i &lt; result.length; i++){

 if(result[i] == null){  
  }else if(result[i]==&quot;&quot;){
  }else{
  lookup[j] = result[i];
  j++
  }
 }
 $.ajax({
        type: &#39;POST&#39;,
        url: &#39;/start&#39;,
        data: &#39;[{&quot;unit&quot;:&quot;&#39;+lookup+&#39;&quot;}]&#39;,
        dataType: &quot;json&quot;,
        contentType: &quot;application/json&quot;,
        success: function () {
           alert(&quot;Data posted.&quot;)
        },
        error: function(){
          alert(&#39;Error posting data.&#39;)
        }
    });
  });
});

The "json" that I send looks like: [{"unit":"something"}].

In the console I can see the data has been posted like this.

答案1

得分: 2

两件事情:

  1. 你正在解组一个 Data 切片,而不是一个 'unit' 切片。
  2. 将 '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:

  1. You are unmarshalling a slice of Data rather than a slice of 'unit'.
  2. 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:&quot;unit&quot;`
}

func receive(w http.ResponseWriter, r *http.Request) {
	dec := json.NewDecoder(r.Body)
	for {
		var d []Data
		if err := dec.Decode(&amp;d); err == io.EOF {
			break
		} else if err != nil {
			log.Println(err)
		}
		log.Printf(&quot;%s\n&quot;, d.Unit)
	}
}

huangapple
  • 本文由 发表于 2015年12月1日 22:30:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/34022839.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定