I have a class that I'll be instantiating a lot from lines of JSON. Something like:
class Something:
def __init__(self, json):
#load all self variables from simplejson.loads(json) here
print self.some_variable_loaded_from_json
I'd like this to be as efficient as possible because this class is loaded hundreds of times a second. I know I can do a for loop with key/value pairs in the dictionary generated from simplejson, but if there's a way to have simplejson just load directly to class variables without that O(n) overhead, that would be awesome.
If you will simply load your JSON data into a Python object, just pass your relevant dictionary to the __init__ method - there you can simply override your instance __dict__ with the passed in dictionary:
>>> import json
>>> json_data = '{"a": "my data"}'
>>> data = json.loads(json_data)
>>> class AutoVar(object):
... def __init__(self, data):
... self.__dict__ = data
...
>>> test = AutoVar(data)
>>> test.a
u'my data'
update It is 2025, and nowadays, the most used pattern for this is to make use of dataclasses. With dataclasses, you have to explicitly define the fields you want in your class, and their expected type - also, any extra keys in the original JSON object will raise an error - so the pattern above can still be useful for some lose situations.
Dataclasses were introduced in Python's stdlib mid last decade to have a standard way to reduce the __init__ boilerplate of assigning arguments to instance fields of the same name, and also adds shortcuts for a nice REPR, and some operators
from dataclasses import dataclass
@dataclass
class MyClass:
a: str
data = {"a": "my data"}
test = MyClass(**data)
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