Below the Radar
Below the Radar

Reputation: 7635

Django - JSON Serialization error

I would like to know why this data retrieved from queryset cannot be serialized in JSON ?

objectList = Layers.objects.all()

data = [objectList.values('id', 'name', 'geom_type')]

jsonData = json.dumps(data)

>>> [{'id': 7, 'geom_type': u'Polygon', 'name': u'ra_general'}, {'id': 6, 'geom_type': u'Polygon', 'name': u'square'}] is not JSON serializable

what is the proper way to achieve that?

Upvotes: 1

Views: 264

Answers (1)

alecxe
alecxe

Reputation: 473753

values() returns a ValuesQuerySet which is not directly serializable via json.dumps().

Convert it to list before dumping:

values = objectList.values('id', 'name', 'geom_type')
data = list(values)  # becomes list of dictionaries
jsonData = json.dumps(data)

Upvotes: 2

Related Questions