Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6706263
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T07:30:00+00:00 2026-05-26T07:30:00+00:00

I think I am missing something small here. I am testing out Python framework

  • 0

I think I am missing something small here. I am testing out Python framework Flask and Flask-MongoAlchemy, and want to convert an entity into JSON output. Here is my code (abstracted):

from flask import Flask
from flaskext.mongoalchemy import MongoAlchemy

try:
    from bson.objectid import ObjectId
except:
    pass

#a bunch of code to open the mongoDB

class ClassA(db.Document):
    title = db.StringField()
    field1 = db.StringField()
    field2 = db.BoolField()

@app.route('/api/classA', methods=['GET'])
def api_list_all
    a = ClassA.query.all()
    result = []
    for b in a:
        result.append(b.wrap())
    print result
    return json.dumps(result)

Without the json.dumps line, the print statement prompt the right result. But only if I run the json.dumps on result, it yields:

TypeError: ObjectId(‘…’) is not JSON serializable

What am I missing?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T07:30:01+00:00Added an answer on May 26, 2026 at 7:30 am

    The result is a mongo document of some sort that contains ObjectId-type content, which you’ll have to tell json how to deserialize. You’ll have the same problem with other mongo-specific types, such as ReferenceField(), EmbeddedDocumentField(), etc.
    You have to write a deserialization function that you can pass to json. What I use is:

    def encode_model(obj, recursive=False):
        if obj is None:
            return obj
        if isinstance(obj, (mongoengine.Document, mongoengine.EmbeddedDocument)):
            out = dict(obj._data)
            for k,v in out.items():
                if isinstance(v, ObjectId):
                    if k is None:
                        out['_id'] = str(v)
                        del(out[k])
                    else:
                        # Unlikely that we'll hit this since ObjectId is always NULL key
                        out[k] = str(v)
                else:
                    out[k] = encode_model(v)
        elif isinstance(obj, mongoengine.queryset.QuerySet):
            out = encode_model(list(obj))
        elif isinstance(obj, ModuleType):
            out = None
        elif isinstance(obj, groupby):
            out = [ (g,list(l)) for g,l in obj ]
        elif isinstance(obj, (list)):
            out = [encode_model(item) for item in obj]
        elif isinstance(obj, (dict)):
            out = dict([(k,encode_model(v)) for (k,v) in obj.items()])
        elif isinstance(obj, datetime.datetime):
            out = str(obj)
        elif isinstance(obj, ObjectId):
            out = {'ObjectId':str(obj)}
        elif isinstance(obj, (str, unicode)):
            out = obj
        elif isinstance(obj, float):
            out = str(obj)
        else:
            raise TypeError, "Could not JSON-encode type '%s': %s" % (type(obj), str(obj))
        return out
    

    Then you’d process the result as:

    return json.dumps(result, default=encode_model)
    

    or something to this effect.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I think I am missing something obvious here, but I can't figure it out.
i think i'm missing something very trivial here. i made an ad-hoc provisioning profile,
I think I'm missing something very obvious and its making my brain hurt. class
I think I might be missing the point of having a logging framework for
I think I am missing something while using the Authlogic gem w/ Rails. To
I think I am missing smth back in my theoretical background on this thing.
I don't think I'm missing anything. Then again I'm kind of a newbie. def
I am trying to do the following but I think I must be missing
I have some problems when I want to use implicit methods to convert a
Hopefully I'm just missing something and this is simple... I have a page that

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.