0

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?

2
  • can't you manually make a json serializable value? {"cities: json.dumps(city_list) } Commented Jan 23, 2015 at 18:42
  • Of course, but there are other methods. I posted a solution. Commented Jan 23, 2015 at 18:44

1 Answer 1

1

Solution: pass by list

city_list = list(Address.objects.values('city').distinct())
jsonData = json.dumps({"cities" : city_list})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.