Python字典json

标签 python google-app-engine

我正在使用 dict 创建一个 json 对象,但我在使用 dict 和 json 时遇到了一些问题!

def get(self):

    players = db.GqlQuery("SELECT * FROM Player")

    playerInfo  = {}



    for player in players:
        email = player.email.encode("utf-8")
        gem =  str(player.gem)

        print email
        print gem

        playerInfo["email"] = email
        playerInfo["gem"] = gem


    b = json.dumps(playerInfo)

    self.response.out.write(b)

出于某种原因,我只收到一个和 for 循环,当我在 for 循环中打印电子邮件时,我收到了 6 个结果,但 playerInfo 的输出只有一组数据。

{"email": "test1", "gem": "0"}

我的预期结果应该是

{"email": "test1", "gem": "0"},{"email": "test2", "gem": "2"}...

最佳答案

你想要的,我想是一个字典列表。这将使您能够存储多个实体:

players = db.GqlQuery("SELECT * FROM Player")

playerInfo  = []

for player in players:
    email = player.email.encode("utf-8")
    gem =  str(player.gem)

    playerInfo.append({"email" :email, "gem": gem})

b = json.dumps(playerInfo)

self.response.out.write(b)

此外,您确实希望避免在您的 AppEngine 应用程序中使用 print。请改用日志记录,因为 print 可能会产生意想不到的副作用。

关于Python字典json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9774796/

相关文章:

python - 我可以 pip 安装 cython 模块并使其 pxds 可用于 cimport 吗?

Python Web3 Ganache - BuildTransaction 上的回溯错误

python - 如何在 Python 中比较区分大小写的字符串?

python - 将对象保存在 MemCache 而不是 Datastore 中

google-app-engine - 拉取任务队列中出现 INVALID_REQUEST 错误

python - Pyspark 将 JSON 读取为字典或结构而不是数据帧/RDD

python - 使用 Python 3 迭代字符串

python - 使用 Google App Engine 时无法导入 Flask

java - 如何从 Google Datastore(Java 中)删除特定记录?

java - 带参数的 Google App Engine ApiMethod 不起作用