[英]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.