Home > Back-end >  "NameError: name 'encode' is not defined " while trying to format an object to j
"NameError: name 'encode' is not defined " while trying to format an object to j

Time:01-11

I'am trying to turn an object into json format by creating a function to first turn that object into a dictionary, which then can be formatted into json. I have also tried to seperate the two functions in the first script into two different classes. So one class with a function to return the object as a dictionary and the other class to provide the conditional statement. Though that doesn't work either. By the way this wasn't included.

import json

class person:
    def __init__(self, name, age):
        self.name = name
        self.age = age


bob = person("Bob", 5)


class encode_Obj:

    def encode(x):
        if isinstance(x, person):
            return {"name": x.name, "age": x.age}
        else:
            raise TypeError("Object of type user is not JSON serializable")


bob_JSON = json.dumps(bob, default=encode)
print(bob_JSON)

I've also totally scratched out that idea and instead tried using JSONEncoder but then it gives me "TypeError: Object of type person is not JSON serializable." Which is the same error it will give if whatever is being formatted into json is not a dictionary, but instead just a normal object. And to note, the returned format doesn't have to be a dictionary, it can be a list for example.

import json
from json import JSONEncoder
class person:
def __init__(self, name1, age1):
    self.name1 = name1
    self.age1 = age1

bob = person("Bob", 5)


class obj_to_json(JSONEncoder):

    def default(self,x):
        if isinstance(x, person):
            return {"name": x.name1, "age": x.age1}

        return super().default(x)

bob_JSON = json.dumps(bob, cls=obj_to_json)
print(bob_JSON)

Feel free to ask for any needed clarificaton.

Thank you.

CodePudding user response:

The correct way to subclass JSONEncoder is to override default. (encoder isn't an existing method; it's not overriding anything and thus not being used.)

class obj_to_json(JSONEncoder):

    def default(self, x):
        if isinstance(x, person):
            return {"name": x.name1, "age": x.age1}

        return super().default(x)

Your first attempt, with encode_Obj, had two problems: one, you try to use a function named encode rather than the instance method of your encode_Obj class; and two, you called the function and passed its return value as the default argument, rather than passing the function itself. Instead, try

def encode(x):
    if isinstance(x, person):
        return {"name": x.name, "age": x.age}
    else:
        raise TypeError("Object of type user is not JSON serializable")


bob_JSON = json.dumps(bob, default=encode)
  •  Tags:  
  • Related