marcelosalloum
marcelosalloum

Reputation: 3531

Send JSON list from Javascript to Django Backend and parsing it properly

I am trying to send a POST request to Django but I am not being able retrieve a json list. I can get the backend to retrieve the items (json objects) from the list but these objects seems unreadable.

Could someone please check my procedure and the results at the end of this thread? I am running out of options here =/

Step 1: Creating the JSON list:

google_news_articles = []

Step 2: Populating the JSON list:

for (each_checkbox in self.coverage_report_google_news_table.checked_rows){
    var each_article    = $(self.coverage_report_google_news_table.checked_rows[each_checkbox]).parents('tr');

    google_news_articles.push({
        date:           each_article.find('.date').text(),
        outlet_domain:  strip(each_article.find('.outlet_domain').text()),
        title:          each_article.find('.title').text(),
        link:           each_article.find('.title').attr('href')
    });
}

Step 3: Making a POST Request:

$.post('/google_news_unsafe_add/',{
    'google_news_articles[]':   google_news_articles,
    'csrfmiddlewaretoken':      $('[name="csrfmiddlewaretoken"]').val()
},function(result){
    if(result.result=='ok'){
        $('#save-status').html("Saved");
    }else{
        $('#save-status').html("An Error Occurred");
    }
});

Step 4: Handling it from the Backend:

def google_news_unsafe_add_view(request):
    print '!!!'
    print request.POST
    print '!!!'
    print '\\\\\\'
    print request.POST.getlist('google_news_articles[]')
    print '\\\\\\'
    return 

Results: Terminal Prints:

!!!
<QueryDict: {u'csrfmiddlewaretoken': [u'nm5NAJyHEvoiFOThSrffU1pETcrQ7oa2'], u'google_news_articles[]': [u'[object Object]', u'[object Object]']}>
!!!
\\\
[u'[object Object]', u'[object Object]']
\\\

All I have is this [u'[object Object]', u'[object Object]'] list and when I try to parse the list, I get:

    json.loads(request.POST.getlist('google_news_articles[]'))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

And when trying to parse the objects, I get:

    print json.loads(each_json)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 383, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

Any hints?

Upvotes: 1

Views: 1419

Answers (1)

marcelosalloum
marcelosalloum

Reputation: 3531

Thanks to Two-Bit Alchemist's comment I realized I should not send a pure JSON object but a serialized JSON object instead.

So I replaced this:

google_news_articles.push({
    date:           each_article.find('.date').text(),
    outlet_domain:  strip(each_article.find('.outlet_domain').text()),
    title:          each_article.find('.title').text(),
    link:           each_article.find('.title').attr('href')
});

for this:

google_news_articles.push(JSON.stringify({
    date:           each_article.find('.date').text(),
    outlet_domain:  strip(each_article.find('.outlet_domain').text()),
    title:          each_article.find('.title').text(),
    link:           each_article.find('.title').attr('href')
}));

And things are now working smoothly =)

Upvotes: 1

Related Questions