为什么此JSON对Python中的此MVC模式无效?

问题描述 投票:-1回答:1

这是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)

对于任何可以阐明我遇到的问题的人,我将不胜感激。

python json
1个回答
0
投票
我取出了model.py文件中的另一行代码。我的JSON文件db.txt不正确,以下代码有效。

[ { "first_name":"Tim", "last_name":"Smith" }, { "first_name":"Bob", "last_name":"Smith" }, { "first_name":"Bill", "last_name":"Smith" }, { "first_name":"John", "last_name":"Smith" } ]

© www.soinside.com 2019 - 2024. All rights reserved.