附加到返回的Google App Engine ndb查询列表

时间:2016-05-21 14:39:46

标签: python json google-app-engine google-cloud-datastore app-engine-ndb

在查询App引擎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只是一个表示而不是实际的返回数据,因此值可能是错误的。

1 个答案:

答案 0 :(得分:1)

问题是你想要的表示是无效的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
}