【问题标题】:Writing list of objects to JSON file将对象列表写入 JSON 文件
【发布时间】:2020-07-18 17:08:03
【问题描述】:

作为作业的一部分,我必须制作一个包含类对象的 JSON 文件。我可以做到,但结果不是我所期望的。

import json    
stList = []


class Student(object):
    neptun_code = ""
    result = 0
    mark = 0


def make_student(neptun_code, result, mark):
    student = Student()
    student.neptun_code = neptun_code
    student.result = result
    student.mark = mark

    stList.append(student)


def create_json():
    json_string = json.dumps([ob.__dict__ for ob in stList])
    with open("./data/student.txt", "w") as file:
        json.dump(json_string, file)

make_student 的示例输入:test_code、test_result、test_mark

这是 student.txt 中的输出:

 "[{\"neptun_code\": \"test_code\", \"result\": \"test_result\", \"mark\": \"test_mark\"}]"

里面有很多不需要的字符。 我想要这样的东西:

[{"neptun_code": "test_code", "result": "test_result", "mark": "test_mark"}]

谁能解释一下如何做到这一点?

【问题讨论】:

标签: python json


【解决方案1】:

您应该使用任一 dumpsdump两者都不是。

dump(我的偏好):

def create_json():
    with open("./data/student.txt", "w") as file:
        json.dump([ob.__dict__ for ob in stList], file)

dumps:

def create_json():
    json_string = json.dumps([ob.__dict__ for ob in stList])
    with open("./data/student.txt", "w") as file:
        file.write(json_string)

附带说明一下,将来您在使用全局对象 stList 时需要注意 scoping

【讨论】:

    【解决方案2】:

    您将字典编码为 JSON 字符串两次。首先你在这里做:

    json_string = json.dumps([ob.__dict__ for ob in stList])
    

    然后再一次,在这里:

    json.dump(json_string, file)
    

    file.write(json_string)改变这一行

    【讨论】:

      猜你喜欢
      • 2013-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 2017-06-29
      相关资源
      最近更新 更多