Python 将对象列表写入JSON文件
作为家庭作业的一部分,我必须制作一个包含类对象的JSON文件。我可以做到,但结果不是我所期望的Python 将对象列表写入JSON文件,python,json,Python,Json,作为家庭作业的一部分,我必须制作一个包含类对象的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 = nep
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
的样本输入:测试代码、测试结果、测试分数
以下是student.txt中的输出:
"[{\"neptun_code\": \"test_code\", \"result\": \"test_result\", \"mark\": \"test_mark\"}]"
里面有很多不想要的角色我想要这样的东西:
[{"neptun_code": "test_code", "result": "test_result", "mark": "test_mark"}]
有人能解释一下怎么做吗?您将字典编码为JSON字符串两次。首先,您可以在此处执行此操作:
json_string = json.dumps([ob.__dict__ for ob in stList])
再一次,这里:
json.dump(json_string, file)
用
file.write(json_string)
更改此行。您将字典编码为json字符串两次。首先,您可以在此处执行此操作:
json_string = json.dumps([ob.__dict__ for ob in stList])
再一次,这里:
json.dump(json_string, file)
使用file.write(json_字符串)
更改此行。您应该使用dumps
或dumps
并非两者都有。
dump
(我的首选):
或转储
:
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
应该使用转储
,或者转储
并非两者都有。
dump
(我的首选):
或转储
:
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)
作为补充说明,将来在使用全局对象时,您将需要小心。dump用于获取Python对象,而不是已经JSONified的字符串。类似的问题:
json.dump
设计用于获取Python对象,而不是已经JSONified的字符串。阅读。类似问题: