Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a JSON string (sent via ajax) into a Python list

I have an array that was converted to a string using JSON.stringify so that I could send the data by ajax to a Python handler. This allowed me to save the data as a sting...brackets, quotes, and all. I need this data in some kind of usable list or array...not just a string. I appreciate any incite you can give, thanks.

The format of the string that is being saved in the database (datastore - using GAE):

["SU15AM","SU3AM","SU4AM","SU45AM","SU4PM","M3AM"]

The javascript/ajax code:

var ids = new Array();

$('.ui-selected').each(function(){ 
    ids.push($(this).attr('value'));    //adds items selected to the array so that they can be passed via ajax
    console.log('**item added to data object**');
});

string_ids = JSON.stringify(ids, null);   //converts array object to a string to pass via ajax

$.ajax({                
    type: "POST",
    url: '/schedule',
    data: {'ids': string_ids},      //string of selected items 
});

Python Handler:

class ScheduleHandler(BaseHandler2):
    time_ids = self.request.get('ids')
    times = AvailableTimes(ids = time_ids)         
    times.put();

Python model:

class AvailableTimes(db.Model): 
    user = db.StringProperty()    
    timezone = db.StringProperty()
    ids = db.StringProperty()
like image 298
Matt Ellis Avatar asked Nov 14 '25 12:11

Matt Ellis


1 Answers

Load it via json.loads():

>>> import json
>>> s = '["SU15AM","SU3AM","SU4AM","SU45AM","SU4PM","M3AM"]'
>>> l = json.loads(s)
>>> l
[u'SU15AM', u'SU3AM', u'SU4AM', u'SU45AM', u'SU4PM', u'M3AM']
>>> type(l)
<type 'list'>  
like image 184
alecxe Avatar answered Nov 17 '25 07:11

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!