开发者

How to use simplejson to serialize and maintain properties?

开发者 https://www.devze.com 2023-02-05 07:05 出处:网络
For a dictionary containing these two key-value pairs: str = StringProperty time = DateTimeProperty I want to serialize it to JSON, store it in the Da开发者_开发问答tastore, and then fetch it, and

For a dictionary containing these two key-value pairs:

str = StringProperty
time = DateTimeProperty

I want to serialize it to JSON, store it in the Da开发者_开发问答tastore, and then fetch it, and deserialize it into the original properties.


Try to do it this way:

d = {
  'str'  : StringProperty,
  'time' : unicode(DateTimeProperty)
}
s = simplejson.dumps(d)
print s


This is simple if your values are strings:

>>> import simplejson
>>> print simplejson.dumps({'str': 'StringProperty', 'time': 'DateTimeProperty'})
{"str": "StringProperty", "time": "DateTimeProperty"}

However, if the values are objects from custom classes (such as the Google App Engine Property classes), they are not JSON serializable.

JSON only serializes simple data types, such as integer/float numbers, booleans, strings, lists/tuples and dictionaries. (See http://www.json.org/ for further details.)

In order to have JSON serializable values, you need to define a way to convert them to simple data types. For example, transforming objects to a tuple containing the class name and the arguments necessary to rebuild them.

0

精彩评论

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