簡體   English   中英

將對象列表寫入 JSON 文件

[英]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"}]

誰能解釋如何做到這一點?

您應該使用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)

附帶說明一下,將來您在使用全局 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM