简体   繁体   中英

json-rpc malformed request with  

I'm building an application that communicates with a django backend using json-rpc. 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. 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:

<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 ; as special characters and so creates an unexpected dictionary in its request.POST variable.

What do I need to do to make sure that the json string doesn't get malformed? I have tried encoding it using the php htmlspecialchars() method, but since that doesn't remove the '&' the problem persists.

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.

Within a query string, & and ; denote the end of a key:value pair. Splitting up your request body on those two characters yields the key:value pairs you see in the Django QueryDict.

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.

I have little experience with Django specifically, but I imagine that somewhere in your view handler you would do something akin to:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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