Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从http POST请求中解组JSON_Python_Json_Http_Go_Marshalling - Fatal编程技术网

Python 从http POST请求中解组JSON

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

我有一个用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 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
参数,您必须向您传递Python
dict
,而不是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))