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

  • Home
  • SEARCH
  • 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 9295811
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T21:41:41+00:00 2026-06-18T21:41:41+00:00

I am looking for a way to encode custom objects to dict in Python

  • 0

I am looking for a way to encode custom objects to dict in Python using a class decorator to provide the name of the variables that should be included in the resulting dict as arguments. With the dict, I would be able to use json.dumps(custom_object_dict) to make the transformation to JSON.

In other words, the idea is to have the following @encoder class decorator:

@encoder(variables=['firstname', 'lastname'], objects=['professor'], lists=['students'])
class Course(Object):
   def __init__(self, firstname, lastname, professor, students):
        self.firstname = firstname
        self.lastname = lastname
        self.professor = professor
        self.students = students

#instance of Course:
course = Course("john", "smith", Professor(), [Student(1), Student(2, "john")])

This decorator would allow me to do something similar to the following:

Option A:

json = json.dumps(course.to_dict())

Option B:

json = json.dumps(course.dict_representation)

…Or something of the like

So the question is: How to write this encoder, where the only real requirements are:

  1. Encoder should only encode variables that are provided through the decorator
  2. Encoder should be able to encode other objects (e.g.: professor inside Courses, if the Professor class also has the decorator @encoder
  3. Should also be able to encode a list of other objects (e.g.: students inside course, counting that the class Students would also have to @encoder decorator)

I have researched different ways of doing that (including creating a class that inherits from json.JSONEncoder), but none seemed to do exactly what I had in mind. Would anyone be able to help me?

Thanks in advance!

  • 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-06-18T21:41:42+00:00Added an answer on June 18, 2026 at 9:41 pm

    Maybe something like this (just a fast sketch):

    #! /usr/bin/python3.2
    
    import json
    
    class Jsonable:
        def __init__ (self, *args):
            self.fields = args
    
        def __call__ (self, cls):
            cls._jsonFields = self.fields
            def toDict (self):
                d = {}
                for f in self.__class__._jsonFields:
                    v = self.__getattribute__ (f)
                    if isinstance (v, list):
                        d [f] = [e.jsonDict if hasattr (e.__class__, '_jsonFields') else e for e in v]
                        continue
                    d [f] = v.jsonDict if hasattr (v.__class__, '_jsonFields') else v
                return d
            cls.toDict = toDict
    
            oGetter = cls.__getattribute__
            def getter (self, key):
                if key == 'jsonDict': return self.toDict ()
                return oGetter (self, key)
            cls.__getattribute__ = getter
    
            return cls
    
    @Jsonable ('professor', 'students', 'primitiveList')
    class Course:
        def __init__ (self, professor, students):
            self.professor = professor
            self.students = students
            self.toBeIgnored = 5
            self.primitiveList = [0, 1, 1, 2, 3, 5]
    
    @Jsonable ('firstname', 'lastname')
    class Student:
        def __init__ (self, firstname, lastname, score = 42):
            self.firstname = firstname
            self.lastname = lastname
            self.score = score
    
    @Jsonable ('title', 'name')
    class Professor:
        def __init__ (self, name, title):
            self.title = title
            self.name = name
    
    p = Professor ('Ordóñez', 'Dra')
    s1 = Student ('Juan', 'Pérez')
    s2 = Student ('Juana', 'López')
    s3 = Student ('Luis', 'Jerez')
    s4 = Student ('Luisa', 'Gómez')
    c = Course (p, [s1, s2, s3, s4] )
    
    print (json.dumps (c.jsonDict) )
    

    You might want to check for other iterables besides list or something like if hasattr (v, __iter__) and not isinstance (v, str).

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

Sidebar

Related Questions

I'm trying to encode instances of a custom python class ISOWeek using python 2.7's
Greetings, I'm looking for a way to encode a string into HTML that uses
I am looking for a way to encode 100 byte on paper and hope
I'm looking for an two-way encryption algorithm to encode an array as a string,
I am using codeigniter and looking a way to enable directly editting of doc
My problem is that I was looking for way to use both storyboard and
I have a series of Moose objects that I'm looking to feed to JSON::XS
I am looking for a simple way to encode an inputted text into Rot13.
I am looking for a way to identify (i.e. encode and decode) a set
we're looking for a standard way to encode a URL given a predefined base

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.