I have classes that I want to represent in JSON
In Javascript, a getter property can be included or excluded of a Json.stringfy() if defined as enumerable: true/false like this:
class Example {
constructor(){
Object.defineProperties(this, {
notEnumerableProperty: {
get: function () {
return 'this is not enumerable';
},
enumerable: false
},
enumerableProperty: {
get: function () {
return 'this is a enumerable';
},
enumerable: true
}
});
}
}
const instance = new Example;
JSON.stringify(instance);
// output "{"enumerableProperty":"this is a enumerable"}"
In Python we can define a getter function as a property like in Javascript using @property decorator. But it doesn't list in a JSON:
#JSONEncoder as seen in https://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable
from json import JSONEncoder
class MyEncoder(JSONEncoder):
def default(self, o):
return o.__dict__
#My class
class Example():
def __init__(self):
self.value = 'this value is enumerable'
@property
def enumerableProperty(self):
return 'It cannot enumerable';
@property
def notEnumerableProperty(self):
return 'It is not enumerable';
instance = Example()
toJson = MyEncoder().encode(instance)
print(toJson)
#output: {"value": "this value is enumerable"}
Is it possible to allow a property be enumerated into a JSON like in Javascript?