【问题标题】:append to returned Google App Engine ndb query list附加到返回的 Google App Engine ndb 查询列表
【发布时间】:2016-05-21 14:39:46
【问题描述】:

当查询 App engine 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只是一个表示,不是实际返回的数据,所以值可能是错误的。

【问题讨论】:

  • 这是一个奇怪的表示,列表应该包含相同类型的元素。不应该像 {result: [], cursor=xxx, more=True}

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


【解决方案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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-27
    • 2017-12-05
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    相关资源
    最近更新 更多