无法在 Go 中解组 post json python 请求

Cannot unmarshal a post json python request in Go

这是我的 python 代码(客户端):

import requests
import json
import datetime
headers = {'Content-type': 'application/json',"Authorization":"Bearer MYREALLYLONGTOKENIGOT" }
url = 'http://127.0.0.1:9210/59c94c860a52840958543027/comment/59dea421c26d684270e9321e'
data = { 'sender' : '59c94c860a52840958543027', 'receiver':'59dea421c26d684270e9321e',
        'score' :5,
        'text':'tres jolie 2'}
data_json = json.dumps(data)
r = requests.post(url=url,headers=headers,json=data_json)
r.json()

这是我的 golang 服务器端代码:

type CommentSent struct {
    Sender    string `json:"sender,omitempty"`
    Receiver  string `json:"receiver,omitempty"`
    Score     int `json:"score,omitempty"`
    Text      string `json:"text,omitempty"`
}


func PostComment(w http.ResponseWriter, r *http.Request) {
    var token string
    token = getToken(r)
    fmt.Println(token)
    vars := mux.Vars(r)
    idUser := vars["idUser"]
    idUserReceiver := vars["idUserReceiver"]
    fmt.Println(idUser)
    fmt.Println(idUserReceiver)
    var commentSend = CommentSend{}
    // body, err := ioutil.ReadAll(r.Body)
    // log.Println(string(body))
    decoder := json.NewDecoder(r.Body)
    err := decoder.Decode(&commentSend)
    if (err != nil){
        Info.Println("error")
        Info.Println(err)

    }

这是给我注释行的内容:

2017/10/12 18:21:29 "{\"sender\": \"59c94c860a52840958543027\", \"score\": 5, \"receiver\": \"59dea421c26d684270e9321e\", \"text\": \"tres jolie 2\"}"

这是我得到的错误:

INFO: 2017/10/12 18:22:32 comment.go:235: json: cannot unmarshal string into Go value of type main.CommentSent

而且我不明白为什么我有这个错误 json 和 python 部分似乎是正确的而且 golang 服务器端似乎也是正确的。

您的整个请求正文是一个带引号的 JSON 字符串,而不是原始的 JSON.

"{\"sender\":....

发送原始 JSON,即:

{"sender":...

或者在你的 Go 程序中取消转义。发送原始 JSON 可能是更好的解决方案。我不知道该怎么做,因为我不是 Python 大师。

我知道有一个涵盖 go 方面的答案,但是当涉及到 Python 时,您不应该将字典转换为 json。请求库应该为你做这件事并确保数据被正确发送。