追加到返回的Google App Engine ndb query lis

2024-10-03 15:21:31 发布

您现在位置:Python中文网/ 问答频道 /正文

当查询appengine ndb数据存储时,我们会得到这样一个列表。你知道吗

[Example(key=Key('Example', 5136918324969472), content=u'hellow', created_on=datetime.datetime(2016, 5, 21, 13, 6, 25, 784956), date=datetime.datetime(2016, 3, 20, 0, 0), modified_on=None, published=True, soft_deleted=False, stars=0), Example(key=Key('Example', 5699868278390784), content=u'hi how r u!', created_on=datetime.datetime(2016, 5, 21, 13, 6, 25, 568392), date=datetime.datetime(2016, 3, 20, 0, 0), modified_on=None, published=True, soft_deleted=False, stars=0)]

然后我们可以将其转换为dict,并对其进行json编码,得到如下结果:

[
  {
    "modifiedOn": null,
    "id": "6051711999279104",
    "stars": 0,
    "tags": [],
    "softDeleted": false,
    "date": "2016-03-20 00:00:00",
    "content": "hello",
    "createdOn": "2016-05-21 13:06:24"
  },
  {
    "modifiedOn": null,
    "id": "4925812092436480",
    "stars": 0,
    "tags": [],
    "softDeleted": false,
    "date": "2016-03-20 00:00:00",
    "createdOn": "2016-05-21 13:06:16"
  }
]

通过使用query.fetch_page()我们可以得到cursor值作为回报。在json编码之前,我想把它放在返回的列表中。我可以通过list.append()方法附加它,但它不能作为键、值。我需要的是:

[
  {
    "modifiedOn": null,
    "id": "6051711999279104",
    "stars": 0,
    "tags": [],
    "softDeleted": false,
    "date": "2016-03-20 00:00:00",
    "content": "hello",
    "createdOn": "2016-05-21 13:06:24"
  },
  {
    "modifiedOn": null,
    "id": "4925812092436480",
    "stars": 0,
    "tags": [],
    "softDeleted": false,
    "date": "2016-03-20 00:00:00",
    "createdOn": "2016-05-21 13:06:16"
  },
  "cursor": "dhiugdgdwidfwiflfsduifewrr3rdufif",
  "more": false
]

谢谢。你知道吗

注意:上面的列表和json只是一个表示,不是实际返回的数据,所以值可能是错误的。你知道吗


Tags: idjsonfalse列表datetimedateonexample
1条回答
网友
1楼 · 发布于 2024-10-03 15:21:31

问题是您想要的表示不是有效的json。你知道吗

你可以通过以下方法得到类似的结果:

results, cursor, more = query.fetch_page()
dict_representation = {"results": results, "cursor": cursor, "more": more}
json_representation = json.dumps(dict_representation)

结果如下:

{
   "results":[
      {
         "modifiedOn":null,
         "id":"6051711999279104",
         "stars":0,
         "tags":[

         ],
         "softDeleted":false,
         "date":"2016-03-20 00:00:00",
         "content":"hello",
         "createdOn":"2016-05-21 13:06:24"
      },
      {
         "modifiedOn":null,
         "id":"4925812092436480",
         "stars":0,
         "tags":[

         ],
         "softDeleted":false,
         "date":"2016-03-20 00:00:00",
         "createdOn":"2016-05-21 13:06:16"
      }
   ],
   "cursor":"dhiugdgdwidfwiflfsduifewrr3rdufif",
   "more":false
}

相关问题 更多 >