Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django : How to serialize dict object to json?

I have this very basic problem,

>>> from django.core import serializers
>>> serializers.serialize("json", {'a':1})
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/pymodules/python2.6/django/core/serializers/__init__.py", line 87, in serialize
    s.serialize(queryset, **options)
  File "/usr/lib/pymodules/python2.6/django/core/serializers/base.py", line 40, in serialize
    for field in obj._meta.local_fields:
AttributeError: 'str' object has no attribute '_meta'
>>> 

How can this be done?

like image 437
Nullpoet Avatar asked Nov 30 '22 10:11

Nullpoet


2 Answers

Also, since you seem to be using Python 2.6, you could just use the json module directly:

import json
data = json.dumps({'a': 1})
like image 119
Nick Bastin Avatar answered Dec 04 '22 03:12

Nick Bastin


from django.utils import simplejson
data = simplejson.dumps({'a': 1})
like image 22
Ignacio Vazquez-Abrams Avatar answered Dec 04 '22 04:12

Ignacio Vazquez-Abrams