user6519628 user6519628 - 5 months ago 39
JSON Question

Calling a class method on a dict object: AttributeError: 'dict' object has no attribute 'get_keyval'

Is it possible to get the key value of the

filter_dict
object kind of that
filter_dict.get_keyval("author")
?:

import json

class Config(dict):
def open_json_file(self, json_string):
load_dict = json.loads(json_string)
return load_dict

def get_keyval(self, key):
search_key = self.load_dict.get(key)
return search_key

filter_dict = Config().open_json_file('{"author" : "Steve", "author_email" : ""}')
print(filter_dict.get_keyval("author"))


Getting:

AttributeError: 'dict' object has no attribute 'get_keyval'


Did the following workaround (but that is not what i want):

import json

class Config():
def open_json_file(self, json_string):
load_dict = json.loads(json_string)
return load_dict

def get_keyval(self, json_string, key):
search_key = json_string.get(key)
return search_key

filter_dict = Config().open_json_file('{"author" : "Steve", "author_email" : ""}')
print(Config().get_keyval(filter_dict, "author"))

Answer

The type of the object returned by Config().open_json_file is not Config, but the plain dict returned by json.loads. Basically, Config is not a class, but just a collection of functions coded as methods. What you want is probably this:

import json

class Config(dict):  # derive from dict to gain get and constructor
  @classmethod
  def from_json_file(cls, json_string):
    """Initialize Config dict from a JSON string"""
    load_dict = json.loads(json_string)
    return cls(load_dict)  # create new Config (dict) filled with JSON content

  def get_keyval(self, key):
    return self.get(key)

filter_dict = Config.from_json_file(...)
print(filter_dict.get_keyval("author"))  # you might want to just call plain filter_dict.get("author") here