Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 857
Kaushik Makwana Avatar asked Apr 26 '17 08:04

Kaushik Makwana


1 Answers

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)
like image 150
Joe Walsh Avatar answered Oct 16 '22 23:10

Joe Walsh