【问题标题】:Issue with reading from json file从 json 文件读取的问题
【发布时间】:2022-01-10 13:06:24
【问题描述】:

我正在处理项目,我正在尝试从 json 文件中写入。不幸的是我发现了一个问题。当我尝试阅读它时,我的文件 pliki.json 中没有得到与此相同的所有内容

pliki.json:
[

      {
            "name": "",
            "pesel": "",
            "choosendir": "Amsterdam-Berlin",
            "lot id": "1",
            "bilet class": "Biznes ",
            "bilet_price": " 68",
            "seat": "5"
      }
]
Function reading:
import csv
from lot import DatabaseofLoty, Lot
import json
from person import Person, Database
from ticket import Ticket
def read_info_aboutpeople(path):
    with open(path, "r") as file_handle:
        people = []
        try:
            rowing = json.load(file_handle)
            for row in rowing:
                name =row["name"],
                print(name)
                pesel = row["pesel"],
                print(pesel)
                choosendir = row["choosendir"]
                print(choosendir)
                lot_id = row["lot id"],
                print(lot_id)
                bilet_class = row["bilet class"],
                bilet_price = row["bilet_price"],
                seat = row["seat"]
                ticket = Ticket(bilet_class,bilet_price)
                person = Person(name, pesel,ticket, choosendir, lot_id, seat)
                people.append(person)
                database = Database(people)
                return database
        except Exception:
            database = Database([])
print(read_info_aboutpeople("pliki.json"))

输出:

('',)
('',)
Amsterdam-Berlin
('1',)

为什么会这样?如何解决这个问题

【问题讨论】:

  • 分配namepesel等时,行尾的逗号有什么意义?
  • 不确定我是否理解您的问题,您想要这个吗?阿姆斯特丹-柏林 1 号?
  • 您的代码很好,只需删除分配行末尾的逗号即可。在 python 3.1 中,每一行都是一个 dict 并且能够获取字段值。你运行的是哪个版本的python?
  • 把这行name =row["name"],改成name =row["name"],以此类推。
  • 除非确实需要,否则不要在行尾使用逗号。修复很简单。

标签: python json class for-loop object


【解决方案1】:

实际上 json 读取有效,但看看这里到底发生了什么:

name = row["name"],
print(type(name)) # <class 'tuple'>

所以实际上你在这里创建一个元素元组,名称是唯一的元素。这就是为什么你会看到奇怪的打印结果,因为你的大多数变量只是元组(这就是为什么当你使用 lot_id 时你的代码可能会爆炸,因为你期望它作为单个 str)。您需要删除逗号才能使代码按预期工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多