Reputation: 736
There is something strange going on when I try to query PostgreSQL database and retrieve values of only one column and then converting it to JSON:
latitude = Places.query.with_entities(Places.latitude).all()
longitude = Places.query.with_entities(Places.longitude).all()
user_schema = UserSchema(many=True, strict = True)
print user_schema
output = user_schema.dump(latitude).data
output = json.dumps([dict(r) for r in output], default=alchemyencoder)
print output #[{"latitude": 28.6333}, {"latitude": 28.6333},...]
print type(output) #<type 'str'>
Although it seems that the result of output is a list of dictionaries and can be iterated to do operations but then in the process of iterating over this dict I was getting errors:
TypeError: string indices must be integers, not str
So, I check the type(output)
and it gives me str
which is why?
Also, When I try to convert it to a float
or int
using
output = float(output)
I get an error:
ValueError: could not convert string to float: [{"latitude": 28.6333}, {"latitude": 28.6333},....]
Upvotes: 1
Views: 194
Reputation: 49862
If you do not want a string, you should not be using json.dumps()
. How about:
[x["latitude"] for x in output]
latitude = Places.query.with_entities(Places.latitude).all()
longitude = Places.query.with_entities(Places.longitude).all()
user_schema = UserSchema(many=True, strict = True)
print user_schema
output = user_schema.dump(latitude).data
print([x["latitude"] for x in output])
Upvotes: 1