Pedro Batista Pedro Batista - 7 months ago 12
Python Question

Cant access value of JSON object

Im doing a little project with flask. Right now, im trying to add options to a select from a JSON object.Despite being able to insert options, i cant access their value

This my flask code:

for dealership in session.query(Dealership).filter_by(ownerID = userId).all():
dealership_list.append({'Name' : dealership.name})

return jsonify(names = dealership_list)


Ajax code:

success:function(result){
$.each(result.names, function(Name, value) {
$('#dealerships').append($("<option/>", {
value: Name,
text: value
}));
});
},

Answer

each item in result.names is a dealership (as defined by your view function).

each dealership is a dict consisting of {"Name":the_name_of_this_dealership}

so $.each(result.names,function(data){console.log(data)} should print each object which is {"Name":some_dealership_name}

so just change it to

success:function(result){
  $.each(result.names, function(dealership) {
      $('#dealerships').append($("<option/>", {
          value: dealership.Name,
          text: dealership.Name
      }));
  });
},

- or -

better yet just change your python code to just return a list of names since thats the only data you are using

dealerships = session.query(Dealership).filter_by(ownerID = userId).all()
names = [dealership.name for dealership in dealerships]
return jsonify(names = names)

and just change your js to

success:function(result){
  $.each(result.names, function(a_dealer_name) {
      $('#dealerships').append($("<option/>", {
          value: a_dealer_name,
          text: a_dealer_name
      }));
  });
}