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: {}
}
}
}
}
}
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.
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.
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.
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.
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.
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? 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'}}
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.
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)
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__)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With