【发布时间】: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"}]
谁能解释一下如何做到这一点?
【问题讨论】:
-
json.dump旨在获取 Python 对象,而不是已经 JSON 化的字符串。阅读docs.python.org/3/library/json.html。