Vikash Kumar
Vikash Kumar

Reputation: 145

append to returned Google App Engine ndb query list

When querying the App engine ndb datastore we get a list like this.

[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)]

then we can convert it to dict and json encode it to get something like this:

[
  {
    "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"
  }
]

By using query.fetch_page() we can get cursor value in return. I want it in returned list before json encoding it. i can just append it by list.append() method but it would not be as key, value. I need it like:

[
  {
    "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
]

Thanks.

Note: above list and json are just a representation not actual returned data so values may be wrong.

Upvotes: 2

Views: 157

Answers (1)

Anjz
Anjz

Reputation: 307

The problem is that the representation you want is not valid json.

You could get something similar by doing:

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

And the result will be something like the following:

{
   "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
}

Upvotes: 1

Related Questions