Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to serialize object in a nested dictionary

Tags:

python

json

I would like to serialize all objects that have the key "manager_objects" in the following dictionary. What is the easiest way to do so?

department {
id: 1,
name: 'ARC',
manager_object: <Object>
sub_department: {
    id: 5,
    name: 'ABC'
    manager_object: <Object>
    sub_department: {
        id: 7,
        name: 'TRW',
        manager_object: <Object>
        sub_department: {
            id: 9,
            name: 'MYT',
            manager_object: <Object>
            sub_deparment: {
                id: 12,
                name: 'NMY'
                manager_object: <Object>
                sub_department: {}
            }

        }
    }

}

}

like image 509
Jiyda Moussa Avatar asked Jun 27 '15 04:06

Jiyda Moussa


People also ask

How do you serialize a dictionary object in Python?

The standard solution for serializing and deserializing a Python dictionary is with the pickle module. The dumps() function serialize a Python object by converting it into a byte stream, and the loads() function do the inverse, i.e., convert the byte stream back into an object.

How do you loop a nested dictionary?

Iterate over all values of a nested dictionary in python We can achieve all this in a simple manner using recursion. Using the function nested_dict_pair_iterator() we iterated over all the values of a dictionary of dictionaries and printed each pair including the parent keys.

Is nested dictionary possible?

Key Points to Remember: Nested dictionary is an unordered collection of dictionary. Slicing Nested Dictionary is not possible. We can shrink or grow nested dictionary as need. Like Dictionary, it also has key and value.

Can dictionary be nested to any depth?

Items are accessed by their position in a dictionary. All the keys in a dictionary must be of the same type. Dictionaries can be nested to any depth. A dictionary can contain any object type except another dictionary.

Is there a way to serialize a list of nested dicts?

While not strictly serialization, json may be reasonable approach here. That will handled nested dicts and lists, and data as long as your data is "simple": strings, and basic numeric types. Show activity on this post. A new alternative to JSON or YaML is NestedText. It supports strings that are nested in lists and dictionaries to any depth.

How to serialize a dictionary object in net?

While serialization in .NET is pretty simple, in general, serialization of a dictionary object is not. Read on to learn how to tackle this tough problem. Join the DZone community and get the full member experience. The serialization and deserialization of .NET objects is made easy by using the various serializer classes that it provides.

What is nested dictionary in Python?

What is Nested Dictionary in Python? In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary. nested_dict = { 'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2'}}

How to slicing nested Dictionary?

Slicing Nested Dictionary is not possible. We can shrink or grow nested dictionary as need. Like Dictionary, it also has key and value. Dictionary are accessed using key.


3 Answers

You can write your own JsonEncoder (or use method described by @PaulDapolito). But, both methods works only if you know type of the item with key manager_object. From docs: To use a custom JSONEncoder subclass (e.g. one that overrides the default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.

# Example of custom encoder
class CustomJsonEncoder(json.JSONEncoder):
    def default(self, o):
        # Here you can serialize your object depending of its type
        # or you can define a method in your class which serializes the object           
        if isinstance(o, (Employee, Autocar)):
            return o.__dict__  # Or another method to serialize it
        else:
            return json.JSONEncoder.encode(self, o)

# Usage
json.dumps(items, cls=CustomJsonEncoder)
like image 181
Akisame Avatar answered Oct 18 '22 23:10

Akisame


Nested dictionaries, enum, date, time and datetime are not serializable in Python by default. Here is the way I handle those types

from datetime import time
from datetime import datetime
from datetime import timedelta
import json
import enum

def to_serializable(val):
    """JSON serializer for objects not serializable by default"""

    if isinstance(val, (datetime, date, time)):
        return val.isoformat()
    elif isinstance(val, enum.Enum):
        return val.value
    elif hasattr(val, '__dict__'):
        return val.__dict__

    return val


def to_json(data):
    """Converts object to JSON formatted string"""

    return json.dumps(data, default=to_serializable)

# example on how to serialize dict
to_json(mydict.__dict__)
like image 41
Vlad Bezden Avatar answered Oct 19 '22 00:10

Vlad Bezden


If your dictionary contains objects that Python/json does not know how to serialize by default, you need to give json.dump or json.dumps a function as its default keyword which tells it how to serialize those objects. By example:

import json

class Friend(object):
    def __init__(self, name, phone_num):
        self.name = name
        self.phone_num = phone_num

def serialize_friend(obj):
   if isinstance(obj, Friend):
       serial = obj.name + "-" + str(obj.phone_num)
       return serial
   else:
       raise TypeError ("Type not serializable")

paul = Friend("Paul", 1234567890)
john = Friend("John", 1234567890)

friends_dict = {"paul": paul, "john": john}
print json.dumps(friends_dict, default=serialize_friend)
like image 3
PaulDapolito Avatar answered Oct 18 '22 22:10

PaulDapolito