开发者

Serializing a class into json for python/gae

[noob question] What's the simplest way to encode a class into JSON in python running on GAE? Not using Django and just whatever built-in stuff that GAE has.

My class is defined like this:

class Sample:
    def __init__(self, myName, myEmail, myLocality, myAliases, myRoles):
        self.name = myName;
        self.email = myEmail;
        self.locality = myLocality
        self.aliases = myAliases;        # this is a list of strings
        self.roles = myRoles             # this is a dictionary

I want to transform it so it looks like this in json:

{sample: 
    name: "a name value",
    email: "whatever email value",
    aliases: [alias1, alias2, alias3],
    locality: "some locality value",
    roles: {
        name: "some name value",
        type: "some type value",
        aux: "additional information"
        }
}

I plan to return this as the response data for the request.

Do I need to come up with a custom Encoder class for my 'Sample' 开发者_开发知识库class?


How about this:

>>> import json
>>> json.dumps(Sample(1, 2, [3, 4], 4, {5: 5, 5: 5}).__dict__)
1: '{"aliases": 4, "locality": [3, 4], "name": 1, "roles": {"5": 5}, "email": 2}'


From json.org

Python:

  1. The Python Standard Library.
  2. simplejson.
  3. pyson.
  4. Yajl-Py.

Links found in http://www.json.org/ (look at the bottom part where the libraries for different languages and platforms are listed)

For the built in way:

http://docs.python.org/library/json.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜