Python 从http POST请求中解组JSON
我有一个用Go编写的简单服务器:Python 从http POST请求中解组JSON,python,json,http,go,marshalling,Python,Json,Http,Go,Marshalling,我有一个用Go编写的简单服务器: package main import ( "encoding/json" "fmt" "github.com/gorilla/mux" "io/ioutil" "net/http" ) type Game struct { RID string `json: "RID"` Country string `json: "Country"` } func postWaitingGames(w h
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"io/ioutil"
"net/http"
)
type Game struct {
RID string `json: "RID"`
Country string `json: "Country"`
}
func postWaitingGames(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Println(err)
}
var game Game
err = json.Unmarshal(body, &game)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%v\n", game)
defer r.Body.Close()
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/wait/", postWaitingGames).Methods("POST")
http.ListenAndServe(":8081", router)
}
以及一个用Python编写的用于测试的简单客户端。代码如下:
import json
import requests
json_to_send = json.dumps({"RID": "8", "Country": "Australia"})
post_headers = {'Content-type': 'application/json'}
addr = "http://127.0.0.1:8081/wait/"
resp = requests.post(url=addr, json=json_to_send, headers=post_headers)
print(resp.status_code)
每次客户端点击服务器时,后者都会产生以下错误:
json: cannot unmarshal string into Go value of type main.Game
我知道
Python版本==3.4
Go版本==1.7
提前谢谢。如果使用
requests.post()
的json
参数,您必须向您传递Pythondict
,而不是json序列化版本-requests
将负责调用json.dumps()
。在这里,您的dict被序列化了两次
另外-在使用
json
参数时-您不需要设置内容类型头,请求
也会处理这个问题 因此,在一些教程(如和)之后,我得到了解组错误,我认为使用(当内容类型为JSON时)有两个选项:
A:
requests.post(url=srvc_url, json=payload)
requests.post(url=srvc_url, data=json.dumps(payload))
B:
requests.post(url=srvc_url, json=payload)
requests.post(url=srvc_url, data=json.dumps(payload))