简体   繁体   English

python json序列化日期时间

[英]python json serialize datetime

First, a simple question on terms, 首先,一个关于条件的简单问题,
Encoding( json.dumps ) means, converting something to json string, Encoding( json.dumps )意味着将某些内容转换为json字符串,
decoding( json.loads ) means, converting json string to json type(?) json.loadsjson.loads )意味着将json字符串转换为json类型(?)


I have a list of objects which I got from 我有从中得到的物品清单

>>> album_image_list = AlbumImage.objects.all().values(*fields)[offset:count]
>>> json.dumps(album_image_list[0], cls=DjangoJSONEncoder)
'{"album": 4, "album__title": "g jfd", "created_at": "2012-08-18T02:23:49Z", "height": 1024.0, "width": 512.0, "url_image": "http://--:8000/media/101ac908-df50-42cc-af6f-b172c8829a31.jpg"}'

but when I try the same on whole list (album_image_list),it fails... 但是当我在整个列表(album_image_list)上尝试相同时,它失败了...

>>> json.dumps(album_image_list, cls=DjangoJSONEncoder)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/python2.6/json/__init__.py", line 237, in dumps
    **kw).encode(obj)
  File "/usr/lib/python2.6/json/encoder.py", line 367, in encode
    chunks = list(self.iterencode(o))
  File "/usr/lib/python2.6/json/encoder.py", line 317, in _iterencode
    for chunk in self._iterencode_default(o, markers):
  File "/usr/lib/python2.6/json/encoder.py", line 323, in _iterencode_default
    newobj = self.default(o)
  File "/home/--/virtualenvs/aLittleArtist/lib/python2.6/site-packages/django/core/serializers/json.py", line 75, in default
    return super(DjangoJSONEncoder, self).default(o)
  File "/usr/lib/python2.6/json/encoder.py", line 344, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: [{'album': 4L, 'album__title': u'g jfd', 'created_at': datetime.datetime(2012, 8, 18, 2, 23, 49, tzinfo=<UTC>), 'height': 1024.0, 'width': 512.0, 'url_image': u'http://--:8000/media/101ac908-df50-42cc-af6f-b172c8829a31.jpg'}, {'album': 4L, 'album__title': u'g jfd', 'created_at': datetime.datetime(2012, 8, 18, 1, 54, 51, tzinfo=<UTC>), 'height': 512.0, 'width': 512.0, 'url_image': u'http://--:8000/media/e85d1cf7-bfd8-4e77-b90f-d1ee01c67392.jpg'}] is not JSON serializable
>>> 

Why does it succeed on one element and fails on the list? 为什么它在一个元素上成功而在列表上失败?

If you want to just dump a dictionary to JSON, just use json.dumps. 如果您只想将字典转储为JSON,请使用json.dumps。 It can easily be made to serialize objects by passing in a custom serialization class - there's one included with Django that deals with datetimes already: 可以通过传入自定义的序列化类来轻松地序列化对象-Django附带了一个已经处理日期时间的类:

from django.core.serializers.json import DjangoJSONEncoder
json.dumps(mydictionary, cls=DjangoJSONEncoder)

.values() doesn't actually return a list. .values()实际上并不返回列表。 It returns a ValuesQuerySet which is not serializable by the json module. 它返回一个不能被json模块序列化的ValuesQuerySet Try converting album_image_list to a list: 尝试将album_image_list转换为列表:

json.dumps(list(album_image_list), cls=DjangoJSONEncoder)

Which DjangoJSONEncoder you are using? 您正在使用哪个DjangoJSONEncoder? it looks like DjangoJSONEncoder may not support encoding list of results. 看起来DjangoJSONEncoder可能不支持结果的编码列表。

Try this: 尝试这个:

JSON Serializing Django Models with simplejson 使用simplejson对JSON模型进行JSON序列化

class DateTimeJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.isoformat()
        else:
            return super(DateTimeJSONEncoder, self).default(obj)

updated_at=DateTimeJSONEncoder().encode(p.updated_at)

This will help you to serialize datetime object 这将帮助您序列化datetime对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM