【问题标题】:Trying to loop through all entries in a datastore object and adding post numbers in dictionary尝试遍历数据存储对象中的所有条目并在字典中添加帖子编号
【发布时间】:2013-12-21 04:23:36
【问题描述】:

我正在将页面的内容解析为 JSON,并且我通过浏览查询后返回的数据存储对象的每个帖子来完成此操作。但是我的循环在返回值之前只经过一次迭代。

代码如下:

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+'}')

正如您所见,循环应该遍历所有帖子,我添加了一个日志行来检查对象中的帖子数量并返回当前帖子的数量。

输入将是一个数据存储对象:<google.appengine.ext.db.GqlQuery object at 0x0427FD90>

这包含 3 个实体:subjectblogday_created

这个函数的输出应该是一个 JSON 对象,其中的帖子是这样排序的:

{
 'allposts:' 
     {'post1': 
            {
             'subject' : ' ... ', 
             'content': ' ... ' , 
             'day' : ' .. ' 
            }
    ,
     .... 
    ,
     'postn' :
          {
           ....
          }
}

【问题讨论】:

    标签: python google-app-engine google-cloud-datastore gql


    【解决方案1】:

    在每次迭代中,您都用

    覆盖json_text
    json_text = json.dumps(json_data)
    

    您可能希望像这样连接结果

    json_text += json.dumps(json_data)
    

    As per the chat,您的要求略有不同。所以,这样的事情对你有用

    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}
    

    【讨论】:

    • 该运算符不适用于字典和字符串类型,购买一般想法应该可以。我必须找到一种方法以某种方式连接字典。使用dict 构造函数和更新可能会有所帮助。
    • @Bhargav 你的意思是说,json_text 是一个字典?
    • 是的,python 字典中不是 JSON 对象吗?
    • @Bhargav json.dumps 会将 python 对象转换为 JSON 字符串。你到底想做什么?
    • 我正在尝试遍历帖子并将它们添加到字典中以转换为 JSON 对象。我尝试使用 += 运算符,但收到错误 unsupported operand type(s) for +=: 'dict' and 'str'
    猜你喜欢
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多