2012-03-19 133 views
1

我正在使用dict來創建一個json對象,但我遇到了dict和json的一些問題!Python字典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的輸出只具有1組數據。

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

我預期的結果應該是

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

您並未創建列表;你只需要爲每個玩家重寫一個字典中的值,然後輸出最後一個值。 – geoffspear 2012-03-19 17:24:12

回答

7

你想要什麼,我認爲是一個字典列表。這將使您存儲多個實體:

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可能會產生意想不到的副作用。

2

試試這個:

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

playerInfo = [] 

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

    playerInfo.append(player_dict) 

b = json.dumps(playerInfo) 

self.response.out.write(b) 
0

要覆蓋字典多次。試試這個:)

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

player_list = [] 



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

    print email 
    print gem 

    playerInfo = {} 

    playerInfo["email"] = email 
    playerInfo["gem"] = gem 
    player_list.append(playerInfo) 


b = json.dumps(player_list) 

self.response.out.write(b) 
0

也許儘可能低的開銷可能會給出更好的輸出是多麼簡單:

L = [] 
for player in players: 
    L.append('{"email": "%s", "gem": "%s"}' % (player.email.encode("utf-8"), str(player.gem)) 
b = ','.join(L) 

只有少數的球員,走高科技路線。更多的玩家,考慮cpu週期,並降低開銷。請原諒上面的任何錯別字。 -stevep