简体   繁体   English

json-rpc格式错误的请求

[英]json-rpc malformed request with  

I'm building an application that communicates with a django backend using json-rpc. 我正在构建一个使用json-rpc与django后端通信的应用程序。 So far all has been working well. 到目前为止,一切进展顺利。 However I've found an anomaly in sending " ". 但是,我在发送“”时发现异常。 As far as I know the request works fine, however django interprets the response badly. 据我所知,请求工作正常,但是django对响应的解释很糟糕。 I've reproduced a simplified request and response below: 我在下面复制了一个简化的请求和响应:

Request: 请求:

{"jsonrpc":"2.0","id":"1","method":"test","params":
{"id":"80","name":"tests","introduction":"hello  there"}}

Django receives: Django收到:

<QueryDict:u'{"jsonrpc":"2.0","id":"1","method":"test","params":
{"id":"80","name":"tests","introduction":"hello ': [u''], u'nbsp': [u''], u'there"}}': [u'']}>

Expected response: 预期回应:

<QueryDict: {u'{"jsonrpc":"2.0","id":"1","method":"test","params":
{"id":"80","name":"tests","introduction":"hello &nbsp;there"}}': [u'']}>

It seems like django interprets the & and the ; 似乎django解释了&和; as special characters and so creates an unexpected dictionary in its request.POST variable. 作为特殊字符,因此会在其request.POST变量中创建意外字典。

What do I need to do to make sure that the json string doesn't get malformed? 我需要怎么做才能确保json字符串不会格式错误? I have tried encoding it using the php htmlspecialchars() method, but since that doesn't remove the '&' the problem persists. 我曾尝试使用php htmlspecialchars()方法对其进行编码,但是由于不能消除'&'问题,问题仍然存在。

Any help will be much appreciated. 任何帮助都感激不尽。

Django is handling the (POST?) request by decoding the body (your json string) as if it were a query string, and not a json. Django通过解码正文(您的json字符串)来处理(POST?)请求,就好像它是查询字符串而不是 json。

Within a query string, & and ; 在查询字符串中, &; denote the end of a key:value pair. 表示key:value对的结尾。 Splitting up your request body on those two characters yields the key:value pairs you see in the Django QueryDict. 在这两个字符上拆分您的请求正文,将产生在Django QueryDict中看到的key:value对。

You need to get hold of the POST request body and explicitly decode it to a dict yourself using either the standard lib json, or simplejson module. 您需要掌握POST请求主体,并使用标准lib json或simplejson模块将其明确解码为dict。

I have little experience with Django specifically, but I imagine that somewhere in your view handler you would do something akin to: 我对Django的经验很少,但我想像您会在视图处理程序中的某处执行以下操作:

try:
    data = json.loads(requesst.raw_post_data)
    ## work with the data...
except ValueError:
    ## do something...

No doubt Django provides a way to move this json handling out of your views, and to somewhere more suitable. 毫无疑问,Django提供了一种将json处理移出您的视图的方法,并将其移至更合适的位置。

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

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