mrbiscuits
mrbiscuits

Reputation: 61

App Engine ndb query to JSON

I'm looking to extract two properties through an ndb query and convert them into JSON. This seems to work when I use print response as this will be the outcome:

[{"LogTime": "2015-09-13T13:26:44.225394Z", "Temp": 40}]

However, when I then use self.response.out.write.response it adds random characters to the start of the JSON file which means the JSON isn't valid.

)]}',
[{"LogTime": "2015-09-13T13:26:44.225394Z", "Temp": 40}]

I've added the bulk of my code below so hopefully any glaring mistakes can be spotted!

entities = OutsideTemp.query().order(-OutsideTemp.LogTime).fetch(1, projection=[OutsideTemp.Temp, OutsideTemp.LogTime])
for entity in entities:
    self.response.headers['Content-Type'] = 'application/json'   
    obj = {
            'LogTime': str(entity.LogTime),
            'Temp': entity.Temp
            } 

    response = obj

print response
self.response.out.write(response)

Upvotes: 0

Views: 281

Answers (2)

ChrisC73
ChrisC73

Reputation: 1853

The prefix you are seeing is being added by the framework you are using (in response.out.write) to implement the AngularJS json security vulnerability workaround (see here).

I am unsure of any python webapp framework that does this by default when writing responses; perhaps this has been added in by a colleague? Check the code for the 'response.out.write' method has not been overridden.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121942

You are not producing JSON at all. Use json.dump() to produce a JSON, having it write directly to the self.response.out object:

data = [{'LogTime': str(entity.LogTime), 'Temp': entity.Temp}
        for entity in entities]
self.response.headers['Content-Type'] = 'application/json'
json.dump(data, self.response.out)

The list comprehension builds up a list of dictionaries first.

Note that the headers need only to be set the once, not for each object in the list of entities.

Upvotes: 2

Related Questions