3

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.

1
  • What is the exact error message you are receiving? Commented Sep 13, 2010 at 1:34

1 Answer 1

7

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}
Sign up to request clarification or add additional context in comments.

1 Comment

If the OP created his JSON using simplejson.dumps() in the first place, this would happen automatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.