Kaushik Makwana
Kaushik Makwana

Reputation: 2576

Converting mongoengine objects to JSON

i tried to fetch data from mongodb using mongoengine with flask. query is work perfect the problem is when i convert query result into json its show only fields name.

here is my code

view.py

from model import Users
result = Users.objects()
print(dumps(result))

model.py

class Users(DynamicDocument):
    meta = {'collection' : 'users'}
    user_name = StringField()
    phone = StringField()

output

[["id", "user_name", "phone"], ["id", "user_name", "phone"]]

why its show only fields name ?

Upvotes: 17

Views: 19221

Answers (1)

Joe Walsh
Joe Walsh

Reputation: 426

Your query returns a queryset. Use the .to_json() method to convert it.

Depending on what you need from there, you may want to use something like json.loads() to get a python dictionary.

For example:

from model import Users
# This returns <class 'mongoengine.queryset.queryset.QuerySet'>
q_set = Users.objects()
json_data = q_set.to_json()

# You might also find it useful to create python dictionaries
import json
dicts = json.loads(json_data)

Upvotes: 41

Related Questions