views:

60

answers:

1

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 parse 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.

+5  A: 

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}
ars
If the OP created his JSON using `simplejson.dumps()` in the first place, this would happen automatically.
Daniel Roseman