Django / python converts my message data from JavaScript

When I send a JSON string to Django from Ajax, it converts it to an invalid JSON format. In particular, if I look in the posts in Firebug, I send:

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

But when I access it in a django request, I see:

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 sending from:

    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 read the POST in django as follows:

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

Any help would be appreciated.

+3
source share
1 answer

How do you encode a JSON string? Single quotes must be double quotes, per 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}
+7
source

Source: https://habr.com/ru/post/1764345/


All Articles