开发者

How to Deserialize JSON back to objects created from db.Model

I want to do something like this guy asked, but I want to deserialize instead of serialize. How to serialize db.Model objects to json?

Is there a library for this? I'm running Google App Engine, and I'm getting a JSON string from appengine-rest-server (http://code.google.com/p/appengine-rest-server/).

I asked the question in a different way here (How to inspect mystery deserialized object i开发者_运维问答n Python) , so I'm hoping by giving the analogy reverse of the above guy's post, it will be more clear what I'm trying to do. If JSON doesn't work, I can use XML instead.


You ought to be able to just instantiate an instance of your desired model by passing the deserialized JSON as kwargs to the constructor. Have a look at the SDK source in google.appengine.ext.db (__init__.py) > Model.__init__ method

eg you could do:

from myapp.models import MyModel

results = '{"firstname": "Neal", "lastname": "Walters"}'
data = json.loads(results)

instance = MyModel(**data)

This is assuming that the keys inf the dict you get back via JSON match exactly the field names, I guess they should do if the JSON is auto-generated from the models originally.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜