这是controller.py文件:
from model import Person
import view
def showAll():
#gets list of all Person objects
people_in_db = Person.getAll()
#calls view
return view.showAllView(people_in_db)
def start():
view.startView()
global input
input = input()
if input == 'y':
return showAll()
else:
return view.endView()
if __name__ == "__main__":
#running controller function
start()
这是此处的model.py文件:
import json
class Person(object):
def __init__(self, first_name = None, last_name = None):
self.first_name = first_name
self.last_name = last_name
#returns Person name, ex: John Doe
def name(self):
return ("%s %s" % (self.first_name,self.last_name))
@classmethod
#returns all people inside db.txt as list of Person objects
def getAll(self):
database = open('db.txt', 'r')
result = []
json_list = json.loads(database.read())
for item in json_list:
item = json.loads(item)
person = Person(item['first_name'], item['last_name'])
result.append(person)
return result
这是这里的view.py文件:
from model import Person
def showAllView(list):
print('In our db we have %i users. Here they are:' % len(list))
for item in list:
print(item.name())
def startView():
print('MVC - the simplest example')
print('Do you want to see everyone in my db?[y/n]')
def endView():
print('Goodbye!')
db.txt文件如下所示:
JSON文件格式正确,因为我正在从文件中读取两项。我在Wikipedia上读到,应该以这种方式构造JSON文件。
此格式直接来自来源:https://en.wikipedia.org/wiki/JSON
{
"first_name": "John",
"last_name": "Smith"
}
我在终端中遇到的错误是:
$ python controller.py
MVC - the simplest example
Do you want to see everyone in my db?[y/n]
y
Traceback (most recent call last):
File "controller.py", line 21, in <module>
start()
File "controller.py", line 15, in start
return showAll()
File "controller.py", line 6, in showAll
people_in_db = Person.getAll()
File "C:\Users\owner\Desktop\model.py", line 18, in getAll
item = json.loads(item)
File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\owner\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
对于任何可以阐明我遇到的问题的人,我将不胜感激。
[
{
"first_name":"Tim",
"last_name":"Smith"
},
{
"first_name":"Bob",
"last_name":"Smith"
},
{
"first_name":"Bill",
"last_name":"Smith"
},
{
"first_name":"John",
"last_name":"Smith"
}
]