Reputation: 4137
I am trying to convert to json a list of values selected via Django queries.
My query is:
city_list = Address.objects.values('city').distinct()
where Address is
class Address(models.Model):
id = models.AutoField(primary_key=True)
streetAddress = models.CharField(max_length=200)
city = models.CharField(max_length=200)
state = models.CharField(max_length=200)
zipCode = models.CharField(max_length=200)
def __unicode__(self):
return str(self.id) + ", " + self.streetAddress + ", " + self.city + ", " + self.state + ", " + self.zipCode
def natural_key(self):
return {"streetAddress":self.streetAddress, "city":self.city, "state":self.state, "zipCode":self.zipCode}
I am trying to convert it to a json like this:
{ "cities" : [ {"city" : "New York"}, {"city" : "Los Angeles"}, {...} ]}
I tried this:
jsonData = json.dumps(city_list)
but the error says that city_list is not JSON serializable. In the error screen, the string looks like:
[{'city': u'Baltimore'}, {'city': u'Berkeley'}, {'city': u'Austin'}...
How can I fix that?
Upvotes: 0
Views: 741
Reputation: 4137
Solution: pass by list
city_list = list(Address.objects.values('city').distinct())
jsonData = json.dumps({"cities" : city_list})
Upvotes: 1