Question

I am parsing the contents of a page into JSON, and I am doing it by going through each post of the datastore object which is returned after the query. But my loop only goes through one iteration before returning the value.

The code for this is:

self.response.headers['Content-Type'] = 'application/json'
    #Getting all the entries of the page
    posts = db.GqlQuery("SELECT * FROM Blog ORDER BY time_created DESC")
    logging.info("Number of posts=" + str(posts.count()) ) 
    #Looping through them all to get the JSON text
    for post in posts:
        json_data = {
            'post' : {
                'subject': post.subject,
                'content': post.blog,
                'day'    : post.day_created.strftime('%d %b %Y')
            }
        }
        json_text = json.dumps(json_data)

    self.write('{"allposts":'+json_text+'}')

As you can see the loop is supposed to go through all the posts, I included a logging line to check the number of posts in the object and it returns the number of posts present.

the input would be a datastore object as such : <google.appengine.ext.db.GqlQuery object at 0x0427FD90>

This contains 3 entities: subject, blog and day_created

The output of this function is supposed to be a JSON object with posts ordered as such :

{
 'allposts:' 
     {'post1': 
            {
             'subject' : ' ... ', 
             'content': ' ... ' , 
             'day' : ' .. ' 
            }
    ,
     .... 
    ,
     'postn' :
          {
           ....
          }
}
Was it helpful?

Solution

On every iteration you are overwriting the json_text with

json_text = json.dumps(json_data)

You might want to concatenate the results like this

json_text += json.dumps(json_data)

As per the chat, your requirement is little different. So, something like this will work for you

for index, post in enumerate(posts, 1):
    json_data["post{}".format(index)] = {
           'subject': post.subject,
           'content': post.blog,
           'day'    : post.day_created.strftime('%d %b %Y')
    }

print {"allposts": json_data}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top