简体   繁体   English

在以下情况下为什么不能解码JSON消息?

[英]Why can't I decode a JSON message in the following situation?

I am trying to send a JSON message from a computer to another one via a post request. 我正在尝试通过发布请求将JSON消息从计算机发送到另一台计算机。 The script which sends the message is the following: 发送消息的脚本如下:

message = {'station':'turn on'}
res = rest.send( 'POST', server_addr + "/newstation", json.dumps(message), {'Content-Type': 'application/json'} )

The rest.send(...) method should be correct as I used it before and it worked fine. rest.send(...)方法应该是正确的,因为我之前使用过它,并且效果很好。

The PC which sends the post request runs Linux, while the receiving one runs Win 8, if that means anything. 发送发布请求的PC运行Linux,而接收请求的PC运行Win 8(如果有任何意义)。

On the receiving machine I have the following: 在接收机上,我有以下内容:

@app.route('/newstation', methods = ['POST'])
def new_station ():
    j_data = request.get_json()
    d = decode_data(j_data)

where decode_data(j_data) is the following 其中decode_data(j_data)是以下内容

def decode_data(j_data):
    d = json.loads(j_data)
    return d

My problem is: whenever I try to send the post request from the first machine the response is "Internal server error" and on the machine with the server the error returned is "TypeError: expected string or buffer". 我的问题是:每当我尝试从第一台计算机发送发布请求时,响应都是“内部服务器错误”,而在带有服务器的计算机上,返回的错误是“ TypeError:期望的字符串或缓冲区”。 Now I am thinking that it may be a matter of encoding of the string. 现在,我认为这可能是字符串编码的问题。

The post request is received and I can print the json content without problems, the issue arises when I try to decode. 收到发布请求,我可以毫无问题地打印json内容,当我尝试解码时会出现问题。

I fixed the issue, it was a mistake on my part (of course). 我解决了这个问题,这是我的错(当然)。 I misunderstood the documentation. 我误解了文档。

@app.route('/newstation', methods = ['POST'])
def new_station ():
   j_data = request.get_json()
   #d = decode_data(j_data)

request.get_json() already returns me a dictionary, so the decode_data function isn't actually needed. request.get_json()已经向我返回了一个字典,因此实际上并不需要解码_数据功能。 I already have the result without the need for json.loads(). 我已经有了不需要json.loads()的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM