I am trying to load simple objects from the json file. But i am getting error in it. below is my code and also the data in json format in db.txt file. I am calling the getAll() function of model.py from some other class.
file: model.py
import simplejson
class Person(object):
def __init__(self, first_name = None, last_name = None):
self.first_name = first_name
self.last_name = last_name
def name(self):
return ("%s %s"%(self.first_name, self.last_name))
@classmethod
def getAll(self):
database = open('db.txt', 'r')
result = []
json_list = simplejson.loads(database.read())
print("json list {}".format(json_list))
for item in json_list:
print("item {}".format(item))
print("type of item {}".format(type(item)))
item = simplejson.loads(item)
person = Person(item['first_name'], item['last_name'])
result.append(person)
return result
file: db.txt
[
{
"first_name":"first name",
"last_name":"last name"
},
{
"first_name":"first name 2",
"last_name":"last name 2"
}
]
ERROR (output):
json list [{'first_name': 'first name', 'last_name': 'last name'}, {'first_name': 'first name 2', 'last_name': 'last name 2'}]
item {'first_name': 'first name', 'last_name': 'last name'}
type of item <type 'dict'>
...
...
item = simplejson.loads(item)
...
...
KeyError: 0
item = simplejson.loads(item)???dictto.loadswhich requires a JSON-validstr....??? In any case that is the source of your error. Just use thedict.item = simplejson.loads(item)and your code will work as you are expecting it to. I still don't understand why you think that line is necessary, or what it is supposed to do.