2

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 in 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.

Community
  • 1
  • 1
NealWalters
  • 17,197
  • 42
  • 141
  • 251
  • Have you seen [`json.load()`](http://docs.python.org/library/json.html#json.load) ? – NullUserException Sep 15 '10 at 04:08
  • Forgot URL above, but the guy said "so it uses (in Python terms) strings, numbers, lists, and dicts (four very basic data types) - and would not deserialize to my desired object. http://stackoverflow.com/questions/3706208/how-to-inspect-mystery-deserialized-object-in-python – NealWalters Sep 15 '10 at 04:16
  • Yes, familiar with json.load() but haven't seen any good/practical examples of how to serialize/deseriaize to/from existing classes. – NealWalters Sep 24 '10 at 20:46

1 Answers1

2

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.

Anentropic
  • 32,188
  • 12
  • 99
  • 147
  • Thanks, but since the question was over a year ago, I either got around it back then or moved on to something else... – NealWalters Feb 09 '12 at 14:09
  • Sure, but the question lives on unanswered... :) hopefully this is useful for people googling for similar issue. The same idea is also possible with Django models. – Anentropic Feb 09 '12 at 15:16