从HTTP POST请求中解析JSON数据

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

Unmarshalling JSON from the http POST request

问题

我有一个用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

我知道这个问题:https://stackoverflow.com/questions/15672556/handling-json-post-request-in-go

Python版本 == 3.4
Go版本 == 1.7

提前谢谢。

英文:

I have a simple server written in 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)
}

And a simple client written in Python for testing purposes. Here's the code:

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)

and everytime the client hits the server, the latter yields this error:

json: cannot unmarshal string into Go value of type main.Game

I'm aware of https://stackoverflow.com/questions/15672556/handling-json-post-request-in-go

Python version == 3.4
Go version == 1.7

Thank you in advance.

答案1

得分: 3

如果使用requests.post()json参数,你必须传递Python的dict,而不是json序列化的版本 - requests会负责调用json.dumps()。这样你的字典就会被序列化两次。

另外,当使用json参数时,你不需要设置content-type头,requests也会处理这个。

英文:

If using requests.post()'s json argument, you must pass you Python dict, not the json-serialized version -requests will take care of calling json.dumps() on it. Here you end up having your dict serialized twice.

Also - always when using the json argument - you don't need to set the content-type header, requests will take care of this too.

答案2

得分: 0

根据你提供的内容,以下是翻译好的部分:

所以,根据这个这个等教程,我遇到了unmarshall错误,我认为在使用**requests**时有两个选项(当内容类型为JSON时):

A:

payload = {
    "userId": "so_cool_user",
}

requests.post(url=srvc_url, json=payload)

B:

requests.post(url=srvc_url, data=json.dumps(payload))
英文:

So, following some tutorials like this and this, I was getting the unmarshall error and I think you have two options using requests (when content type is JSON):

payload = {
    "userId": "so_cool_user",
}

A:

requests.post(url=srvc_url, json=payload)

B:

requests.post(url=srvc_url, data=json.dumps(payload))

huangapple
  • 本文由 发表于 2017年1月5日 21:17:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/41486136.html
匿名

发表评论

匿名网友

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

确定