Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: "TypeError: [] is not JSON serializable" Why?

How can this be that this error was raised? I entered this:

def json(self):     return json.dumps(         {             'items': self.items         }     ) 

and got that error (because self.items was an empty queryset (Django)

but then,

def json(self):     return json.dumps(         {             'items': []  # Pass in empty list to prove that the error was idiotic.         }     ) 

worked fine (which at least proves that the error message is worthless)

Is this because the queryset defines repr() and returns '[]' as a string when it's empty or something ridiculous like that?

like image 210
orokusaki Avatar asked Feb 11 '10 07:02

orokusaki


People also ask

Why is a set not JSON serializable?

The Python "TypeError: Object of type set is not JSON serializable" occurs when we try to convert a set object to a JSON string. To solve the error, convert the set to a list before serializing it to JSON, e.g. json. dumps(list(my_set)) . Here is an example of how the error occurs.

Is not JSON serializable TypeError?

The Python "TypeError: Object of type method is not JSON serializable" occurs when we try to serialize a method to JSON. To solve the error, make sure to call the method and serialize the object that the method returns.

What is JSON serializable in Python?

Serialization is the process of transforming objects of complex data types (custom-defined classes, object-relational mappers, datetime, etc.) to native data types so that they can then be easily converted to JSON notation.

Are Python lists JSON serializable?

Any Python object can be serialized into JSON format and vice versa. All popular programming languages support converting objects into JSON and vice versa. Without involving any objects as well, JSON strings can be formed and interchanged between any two processes, client and server as data.


2 Answers

Querysets are not serializable out-of-the-box. If you try list(self.items) instead of just self.items, that should work as long as the items themselves are JSON-serializable.

Update: It will raise an exception even if it isn't empty. I don't think it'll be accepted as a Django bug, though of course you can try; the simplest answer is to force evaluation using list(qs), as I've already said.

like image 166
Vinay Sajip Avatar answered Sep 24 '22 06:09

Vinay Sajip


This is very frustrating. Django's serialization complains about everything that isn't a query set and json.dumps complains about objects from Django's ORM support.

>>> from cluster.models import Account >>> import json >>> json.dumps(Account.objects.all()[0]) Traceback (most recent call last):   File "<console>", line 1, in <module>   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 231, in dumps     return _default_encoder.encode(obj)   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 201, in encode     chunks = self.iterencode(o, _one_shot=True)   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 264, in iterencode     return _iterencode(o, 0)   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 178, in default     raise TypeError(repr(o) + " is not JSON serializable") TypeError: <Account: 9de5-2653-000d-81a3 => [email protected]> is not JSON serializable 

Versus

>>> serializers.serialize("json", [clusters]) Traceback (most recent call last):   File "<console>", line 1, in <module>   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/serializers/__init__.py", line 91, in serialize     s.serialize(queryset, **options)   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/serializers/base.py", line 41, in serialize     for field in obj._meta.local_fields: AttributeError: 'QuerySet' object has no attribute '_meta' 
like image 44
Ted Dunning Avatar answered Sep 24 '22 06:09

Ted Dunning