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 632773
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T20:06:47+00:00 2026-05-13T20:06:47+00:00

I’m trying to serialize a list of python objects with JSON (using simplejson) and

  • 0

I’m trying to serialize a list of python objects with JSON (using simplejson) and am getting the error that the object “is not JSON serializable”.

The class is a simple class having fields that are only integers, strings, and floats, and inherits similar fields from one parent superclass, e.g.:

class ParentClass:
  def __init__(self, foo):
     self.foo = foo

class ChildClass(ParentClass):
  def __init__(self, foo, bar):
     ParentClass.__init__(self, foo)
     self.bar = bar

bar1 = ChildClass(my_foo, my_bar)
bar2 = ChildClass(my_foo, my_bar)
my_list_of_objects = [bar1, bar2]
simplejson.dump(my_list_of_objects, my_filename)

where foo, bar are simple types like I mentioned above. The only tricky thing is that ChildClass sometimes has a field that refers to another object (of a type that is not ParentClass or ChildClass).

What is the easiest way to serialize this as a json object with simplejson? Is it sufficient to make it serializable as a dictionary? Is the best way to simply write a dict method for ChildClass? Finally, does having the field that refer to another object significantly complicate things? If so, I can rewrite my code to only have simple fields in classes (like strings/floats etc.)

thank you.

  • 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-13T20:06:47+00:00Added an answer on May 13, 2026 at 8:06 pm

    I’ve used this strategy in the past and been pretty happy with it: Encode your custom objects as JSON object literals (like Python dicts) with the following structure:

    { '__ClassName__': { ... } }
    

    That’s essentially a one-item dict whose single key is a special string that specifies what kind of object is encoded, and whose value is a dict of the instance’s attributes. If that makes sense.

    A very simple implementation of an encoder and a decoder (simplified from code I’ve actually used) is like so:

    TYPES = { 'ParentClass': ParentClass,
              'ChildClass': ChildClass }
    
    
    class CustomTypeEncoder(json.JSONEncoder):
        """A custom JSONEncoder class that knows how to encode core custom
        objects.
    
        Custom objects are encoded as JSON object literals (ie, dicts) with
        one key, '__TypeName__' where 'TypeName' is the actual name of the
        type to which the object belongs.  That single key maps to another
        object literal which is just the __dict__ of the object encoded."""
    
        def default(self, obj):
            if isinstance(obj, TYPES.values()):
                key = '__%s__' % obj.__class__.__name__
                return { key: obj.__dict__ }
            return json.JSONEncoder.default(self, obj)
    
    
    def CustomTypeDecoder(dct):
        if len(dct) == 1:
            type_name, value = dct.items()[0]
            type_name = type_name.strip('_')
            if type_name in TYPES:
                return TYPES[type_name].from_dict(value)
        return dct
    

    In this implementation assumes that the objects you’re encoding will have a from_dict() class method that knows how to take recreate an instance from a dict decoded from JSON.

    It’s easy to expand the encoder and decoder to support custom types (e.g. datetime objects).

    EDIT, to answer your edit: The nice thing about an implementation like this is that it will automatically encode and decode instances of any object found in the TYPES mapping. That means that it will automatically handle a ChildClass like so:

    class ChildClass(object):
        def __init__(self):
            self.foo = 'foo'
            self.bar = 1.1
            self.parent = ParentClass(1)
    

    That should result in JSON something like the following:

    { '__ChildClass__': {
        'bar': 1.1,
        'foo': 'foo',
        'parent': {
            '__ParentClass__': {
                'foo': 1}
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 315k
  • Answers 315k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Yep, that's exactly what macros do. Here's a straightforward macro… May 13, 2026 at 11:18 pm
  • Editorial Team
    Editorial Team added an answer The default ASP.NET MVC 2 template of Visual Studio includes… May 13, 2026 at 11:18 pm
  • Editorial Team
    Editorial Team added an answer Type t = obj.GetType(); Although I don't think there's any… May 13, 2026 at 11:18 pm

Related Questions

I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I want use html5's new tag to play a wav file (currently only supported
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I've got a string that has curly quotes in it. I'd like to replace
In order to apply a triggered animation to all ToolTip s in my app,

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.