-1

I've got a big class in python, but I'll make it shorter:

class Server:
    name = ""
    discordId = 0
    ownerId = 0
    welcome_message = None
    lang = "en"

And I also have an encoder function:

def encoder(cl):
    if isinstance(cl, Server):
        jsonList = {
            "name": cl.name,
            "discordId": cl.discordId,
            "ownerId": cl.ownerId,
            "welcome_message": cl.welcome_message,
            "lang": cl.lang
        }
        return jsonList

But when I try to serialize it, I just cannot.

server = Server()
server.name = guild.name
server.discordId = guild.id
server.ownerId = guild.owner.id
server.lang = "en"

json.dumps(encoder(server))

I get this

Ignoring exception in on_guild_join
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/folder/bot.py", line 40, in on_guild_join
    json.dumps(encoder(server))
  File "/usr/lib/python3.8/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.8/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type type is not JSON serializable

Is there anything I'm missing?

Nekidev
  • 69
  • 1
  • 1
  • 8

2 Answers2

1

Don't convert None fields

Source: https://stackoverflow.com/a/15538391/13277578

import json

class Server():
    def toJSON(self):
        return json.dumps(self, default=lambda o: o.__dict__,
            sort_keys=True, indent=4)

    name = ""
    discordId = 0
    ownerId = 0
    welcome_message = None
    lang = "en"

server = Server()
server.name = ""
server.discordId = 5
server.ownerId = 5
server.lang = "en"


print(server.toJSON())

# {
#      "discordId": 5,
#      "lang": "en",
#      "name": "",
#      "ownerId": 5
# }
jacob galam
  • 781
  • 9
  • 21
-1

You're looking for a dataclass, or you need to override the __init__ method of your class. Also, why not just add a method to the class called to_dict?

import json

class Server:
    def __init__(self,
        name = "",
        discordId = 0,
        ownerId = 0,
        welcome_message = None,
        lang = "en"):
            self.name = name
            self.discordId = discordId
            self.ownerId = ownerId
            self.welcome_message = welcome_message
            self.lang = lang
    
    def to_dict(self):
        return {
            "name": self.name,
            "discordId": self.discordId,
            "ownerId": self.ownerId,
            "welcome_message": self.welcome_message,
            "lang": self.lang
        }
        
server = Server(guild.name, guild.id, guild.owner.id, "en")

print(json.dumps(server.to_dict()))
Jab
  • 26,853
  • 21
  • 75
  • 114
  • But why was there an error "TypeError: Object of type type is not JSON serializable" and why does this fix that error? – mkrieger1 Dec 16 '20 at 20:41
  • Is this not the same as the other with the encoder function, only that this has the func inside the class? – Nekidev Dec 16 '20 at 20:44