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

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

问题描述

使用

 从django.utils导入simplejson 

在派生自 db.Model 的类型的对象上抛出异常。如何绕过这个?

解决方案

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

  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 = [] ;
为obj中的项目:
items.append(dumps(item))
return'['+','。join(items)+']'
elif isinstance( obj,datetime.datetime):
returnnew Date('%s')%obj.ctime()
properties = [];
for property in dir(obj):
if property [0]!='_':
value = obj .__ getattribute __(property)
valueClass = str(value .__ class__ )
如果没有((valueClass中的'function'或valueClass中的'built')或valueClass中的'method'):
value = dump(value)
if value! = None:
properties.append('+ property +':+ value)
if len(properties)== 0:
return str(obj)
else:
return'{'+','。join(properties)+'}'


When using

from django.utils import simplejson

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

解决方案

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天全站免登陆