[英]Writing list of objects to JSON file
作为我作业的一部分,我必须制作一个 JSON 文件,其中包含 class 对象。 我可以做到,但结果不是我所期望的。
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 中的 output:
"[{\"neptun_code\": \"test_code\", \"result\": \"test_result\", \"mark\": \"test_mark\"}]"
里面有很多不需要的字符。 我想要这样的东西:
[{"neptun_code": "test_code", "result": "test_result", "mark": "test_mark"}]
谁能解释如何做到这一点?
您应该使用dumps
或dump
。 不是都。
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)
附带说明一下,将来您在使用全局 object stList
时需要注意范围。
您将字典编码为 JSON 字符串两次。 首先,您在这里执行此操作:
json_string = json.dumps([ob.__dict__ for ob in stList])
然后再一次,在这里:
json.dump(json_string, file)
用file.write(json_string)
改变这一行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.