如何将 db.Model 对象序列化为 json? [英] How to serialize db.Model objects to json?

查看:31
本文介绍了如何将 db.Model 对象序列化为 json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用时

from django.utils import simplejson

对于从 db.Model 派生的类型的对象,它会抛出异常.如何规避?

on objects of types that derive from db.Model it throws exceptions. How to circumvent this?

推荐答案

由于找不到合适的解决方案,我自己写了一个,它不完全是一个 JSON 序列化器,而是一个 Javascript 序列化器

Since I could not find an appropriate solution I wrote my own, which is not exactly a JSON serializer, but a Javascript serializer

from google.appengine.ext import db
from google.appengine.api.datastore_types import *

def dumpStr(obj):
    return "'" + obj + "'"

def dumps(obj):
    if isinstance(obj, str):
        return dumpStr(obj)
    elif obj == None:
        return None
    elif isinstance(obj, list):
        items = [];
        for item in obj:
            items.append(dumps(item))
        return '[' + ','.join(items) + ']'
    elif isinstance(obj, datetime.datetime):
        return "new Date('%s')" % obj.ctime()
    properties = [];
    for property in dir(obj):
        if property[0] != '_':
            value = obj.__getattribute__(property)
            valueClass = str(value.__class__)
            if not(('function' in valueClass) or ('built' in valueClass) or ('method' in valueClass)):
                value = dumps(value)
                if value != None:
                    properties.append("'" + property + "':" + value)
    if len(properties) == 0:
        return str(obj)
    else:
        return '{' + ','.join(properties) + '}'

这篇关于如何将 db.Model 对象序列化为 json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆