I'm learning Python but have a good 13+ years experience in other languages.
Today I studied the JSON serialization in Python and as far as I understand, not just the default json
module but also every other custom one out there cannot serialize an arbitrary class. For example:
import ujson
class Person:
def __init__(self, name, age, learnsPython, controllers):
self.name = name
self.age = age
self.learnsPython = learnsPython
self.controllers = controllers
person = Person("Mike", 34, True, ['XboX', 'Super Nintendo'])
print(ujson.dumps(person))
This doesn't work, regardless of a serializer module I'd use.
Perhaps it's something I just missed at a conceptual level. Or possibly, I'm just spoiled with Java or, say, dotnet having e.g. [System.Web.Extensions]System.Web.Script.Serialization.JavaScriptSerializer.Deserialize<T>()
for classic .NetFramework or System.Text.Json.JsonSerializer.Deserialize<T>()
for Core.
You just take a type you wish, and [de]serialize it around as much as you need.
Main question: does simple OOB [de]serialization really not exist in Python for any arbitrary type? And if so then why?
Side note after 2 min googling: I can clearly see the way of doing such serializer by simply using vars()
on any type, possibly recursively, even with standard json
module. And assume the deserialization is also possible in a similar manner, through setattr()
. So why nobody does this?