Brian Li
Brian Li

Reputation: 573

Python dictionary json

I am using dict to create a json object but I am having some issue with dict and 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 some reason I only received one and the for loop, and when I print email in the for loop I received 6 results but the output of playerInfo only has 1 set of data.

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

My expected result should be

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

Upvotes: 1

Views: 870

Answers (4)

stevep
stevep

Reputation: 959

maybe lowest possible overhead might be better given how simple the output is:

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

Only a few players, go the tech route. More players, think about cpu cycles, and lower your overhead. Pardon any typos above. -stevep

Upvotes: 0

Maria Zverina
Maria Zverina

Reputation: 11173

You are overwriting the dictionary many times. Try this instead :)

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)

Upvotes: 0

Adam Crossland
Adam Crossland

Reputation: 14213

What you want, I think is a list of dictionaries. That will enable you to store multiple entities:

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)

Also, you really want to avoid using print in you AppEngine applications. Use logging instead, as print can have unintended side-effects.

Upvotes: 7

g.d.d.c
g.d.d.c

Reputation: 48048

Try this instead:

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)

Upvotes: 2

Related Questions