【问题标题】:How to JSON encode? [duplicate]如何进行 JSON 编码? [复制]
【发布时间】:2011-03-23 05:46:06
【问题描述】:

可能重复:
How to JSON encode Entities?

我开始使用 Google App Engine。我想让 AJAX 聊天像 Twitter。

class ChatMessage(db.Model):
  message = db.StringProperty()
  created = db.DateTimeProperty(auto_now=True)

服务器 JSON 编码响应,

class RPCHandler(webapp.RequestHandler):
  def get(self):
    chat_list = {'message':'Hello!'}
    self.response.out.write(simplejson.dumps(chat_list))

结果:你好!

没关系。但是替换RPCHandler

class RPCHandler(webapp.RequestHandler):
  def get(self):
    newchat = ChatMessage(message="Hi!")
    newchat.put()
    que = db.Query(ChatMessage).order('-created')
    chat_list = que.fetch(limit=1)

    self.response.out.write(simplejson.dumps(chat_list))

结果:错误。服务器不可访问(get)

如何对数据库中的数据进行 JSON 编码?

【问题讨论】:

标签: python json google-app-engine


【解决方案1】:

查看 Python 文档:

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

(具体看API方法'json.dump')

【讨论】:

    【解决方案2】:

    Python 有一个名为 json 的模块,它可以自动序列化和反序列化字典、列表和其他原生 Python 对象(或复杂类型,如果您提供接口)。

    如果您可以将数据库查询的结果作为字典返回,那么您可以简单地使用:

    import json
    as_json = json.dumps(dictionary)
    

    如需进一步参考,请访问官方json module documentation。

    【讨论】:

      【解决方案3】:

      您真的应该看看 Djano 在其 django.core.serializers.json 模块中处理它的方式。

      【讨论】:

        猜你喜欢
        • 2016-12-21
        • 2018-08-02
        • 2011-07-20
        • 2011-09-09
        • 2023-03-31
        • 2014-02-04
        • 2022-01-11
        • 2014-03-25
        • 2017-05-12
        相关资源
        最近更新 更多