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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T02:26:28+00:00 2026-06-18T02:26:28+00:00

The following class is implemented to provide a generic object that can be passed

  • 0

The following class is implemented to provide a generic object that can be passed through network as a json-encoded dictionary. I’m actually trying to json encode a dict (!) but it won’t work.

I know it will work with custom encoder class, but I don’t see why it’s necessary when I’m just encoding a dict.

Can someone explain the TypeError or offer a way to encode this without subclassing JSONEncoder?

Here is the bad behavior.

>>> def tree(): return CustomDict(tree)
>>> d = tree()
>>> d['one']['test']['four'] = 19
>>> d.dict
{ 'one' : { 'test': {'four': 19}}}
>>> type(d.dict)
<type 'dict'> 
>>> import json
>>> json.dumps(d.dict)
# stacktrace removed
TypeError: {'one': {'test': {'four': 19}}} is not JSON serializable
>>> normal_d = {'one': {'test': {'four': 19}}}
>>> type(normal_d)
<type 'dict'>
>>> json.dumps(normal_d)
"{'one': {'test': {'four': 19}}}"
>>> normal_d == d
True

I would love to be able to do the following

>>>> json.dumps(dict(d))
"{'one': {'test': {'four': 19}}}"

but I added the dict property to ‘force it’ (didn’t work obviously). Now it’s an even bigger mystery. Here is the code for the CustomDict class

class CustomDict(collections.MutableMapping):                                
    """                                                                         
    A defaultdict-like object that can also have properties and special methods 
    """                                                                         

    def __init__(self, default_type=str, *args,  **kwargs):                     
        """                                                                     
        instantiate as a default-dict (str if type not provided). Try to update 
        self with each arg, and then update self with kwargs.                                                                

        @param default_type: the type of the default dict                       
        @type default_type: type (or class)                                     
        """                                                                     
        self._type = default_type                                               
        self._store = collections.defaultdict(default_type)                     
        self._dict = {}                                                         

        for arg in args:                                                        
            if isinstance(arg, collections.MutableMapping):                     
                self.update(arg)                                                

        self.update(kwargs)                                                     

    @property                                                                   
    def dict(self):                                                             
        return self._dict                                                       

    def __contains__(self, key):                                                
        return key in self._store                                               

    def __len__(self):                                                          
        return len(self._store)                                                 

    def __iter__(self):                                                         
        return iter(self._store)                                                

    def __getitem__(self, key):                                                 
        self._dict[key] = self._store[key]                                      
        return self._store[key]                                                 

    def __setitem__(self, key, val):                                            
        self._dict[key] = val                                                   
        self._store[key] = val                                                  

    def __delitem__(self, key):                                                 
        del self._store[key]                                                    

    def __str__(self):                                                          
        return str(dict(self._store))   
  • 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-18T02:26:29+00:00Added an answer on June 18, 2026 at 2:26 am

    You want to make your type a subclass of dict, not of collections.MutableMapping, really.

    Even better still, use collections.defaultdict directly instead, it already is a subclass of dict and can be used to implement your tree ‘type’ easily:

    from collections import defaultdict
    
    def Tree():
        return defaultdict(Tree)
    
    tree = Tree()
    

    Demonstration:

    >>> from collections import defaultdict
    >>> def Tree():
    ...     return defaultdict(Tree)
    ... 
    >>> tree = Tree()
    >>> tree['one']['two'] = 'foobar'
    >>> tree
    defaultdict(<function Tree at 0x107f40e60>, {'one': defaultdict(<function Tree at 0x107f40e60>, {'two': 'foobar'})})
    >>> import json
    >>> json.dumps(tree)
    '{"one": {"two": "foobar"}}'
    

    If you must add your own methods and behaviour, then I’d subclass defaultdict and build upon that base:

    class CustomDict(defaultdict):
        pass
    

    As this is still a subclass of dict, the json library will happily convert that to a JSON object without special handling.

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

Sidebar

Related Questions

I have the following Strategy Pattern implemented: public abstract class RetrievalStrategy { public abstract
I have the following tricky problem: I have implemented a (rather complicated) class which
According to CSharp Language Specification. An interface defines a contract that can be implemented
I have a generic class which represents a fragment of text. That fragment of
I have an interface A , which class B implements. The following generic method
I am doing the following class RuleObject implements Comparable{ @Override public String toString() {
I have the following class (from a simple Spring tutorial) public class CarValidator implements
I have the following factory class: public class MessagePresenterCreator implements IPresenterFactory{ @Override public MessagePresenter
I have the following class signature: public class LoopIterator<E> implements Iterator<E> . I have
I'm trying to implement a delegate class following Herb Sutter's Example . There is

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.