python - 如何序列化一个数组?

标签 python json django python-3.x

错误发生在 Controller 函数调用中。返回一个数据数组。我需要将这个数组传递给模板。

views.py:

def new_authors(request):   
    new_authors = UserProfile.get_new_authors_entries()

    # UserProfile.get_new_authors_entries() retrun:
    #[
    #   {
    #       'id': 4, 
    #       'username': 'zzzzzz'
    #   }, 
    #   {
    #       'id': 5, 
    #       'username': 'wwwwww'
    #   }
    #]

    return HttpResponse(json.dumps(new_authors), content_type='application/json')   

但是我收到以下错误信息:

File "/usr/lib/python3.4/json/encoder.py", line 173, in default
    raise TypeError(repr(o) + " is not JSON serializable") TypeError: [{'id': 4,  'username': 'zzzzzz'}, {'id': 5, 'username': 'wwwwww'}] is not JSON serializable

模型.py:

class UserProfile(User):            


    @classmethod
    def get_new_authors_entries(self, cut_begin=0, cut_end=2):
        return self.objects.filter(is_active=1, is_superuser=0).values('id', 'username')[cut_begin:cut_end] 

最佳答案

因为这个post建议,您可以使用 json.dumps 的默认参数来处理您的问题:

>>> dthandler = lambda obj: (
...     obj.isoformat()
...     if isinstance(obj, datetime.datetime)
...     or isinstance(obj, datetime.date)
...     else None)
>>> json.dumps(datetime.datetime.now(), default=dthandler)
'"2010-04-20T20:08:21.634121"'

我在序列化 datetime 对象时遇到了同样的问题,这很有帮助。

和平

关于python - 如何序列化一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26299854/

相关文章:

python - 使用 TF-IDF 方案从给定句子中提取关键短语的任何有效解决方法?

Swift 3 中的 JSON 解析错误

javascript - 防止对 PHP 的虚假循环 ajax 请求

python - 我可以在pycharm的断点处进入交互模式吗

python - 在同一个 apache 上一起使用基于 django 的 mod_wsgi 和基于原始 python 的 mod_python

python - django-图像裁剪不起作用

python - 如何比较 Python 中两个不同元组列表中的键?

python - 如果 "this"是答案,则返回上一行

java - 如何在 postgresql dbms 中选择数据进行数组?

python - 为 Pandas 设置差异