开发者

Django/python is converting my post data from JavaScript

When I post a JSON string to Django by Ajax, it converts it into an invalid JSON format. Specifically, if I look in the post data in Firebug I am sending:

info    {'mid':1,'sid':27,'name':'aa','desc':'Enter info' }

Yet when I access it in the django request I am seeing:

u'{\'mid\':1,\'sid\':27,\'name\':\'aa\',\'desc\':\'Enter Info\'}

When I try to p开发者_StackOverflowarse this with json.loads it dies with an invalid JSON message.

I am posting with:

    data.info = "{'mid':1,'sid':27,'name':'aa','desc':'Enter info' }";
    $.ajax({url: cmdAjaxAddress,
            type: "POST",
            data: data,
            success: function(txt) {
                result = txt;
            },
            async: false });

I am reading the POST in django like this:

if request.is_ajax() and request.method == 'POST':
    infoJson = request.POST['info']
    info = json.loads(infoJson);

Any help would be appreciated.


How are you encoding your JSON string? The single quotes need to be double quotes, per the spec:

In [40]: s1 = "{'mid':1,'sid':27,'name':'aa','desc':'Enter info' }"

In [41]: simplejson.loads(s1)
JSONDecodeError: Expecting property name: line 1 column 1 (char 1)

In [42]: s2 = '{"mid":1,"sid":27,"name":"aa","desc":"Enter info" }'

In [43]: simplejson.loads(s2)
Out[43]: {'desc': 'Enter info', 'mid': 1, 'name': 'aa', 'sid': 27}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜