简体   繁体   English

将对象列表写入 JSON 文件

[英]Writing list of objects to JSON file

As part of my homework I have to make a JSON file with class objects in it.作为我作业的一部分,我必须制作一个 JSON 文件,其中包含 class 对象。 I could do it, but the result is not that i expected.我可以做到,但结果不是我所期望的。

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)

Sample inputs for make_student : test_code, test_result, test_mark make_student的示例输入: test_code、test_result、test_mark

Here is the output in student.txt:这是 student.txt 中的 output:

 "[{\"neptun_code\": \"test_code\", \"result\": \"test_result\", \"mark\": \"test_mark\"}]"

there are plenty of unwanted characters in it.里面有很多不需要的字符。 I would like to have something like this:我想要这样的东西:

[{"neptun_code": "test_code", "result": "test_result", "mark": "test_mark"}]

Can anyone explain how to do this?谁能解释如何做到这一点?

You should use either dumps , or dump .您应该使用dumpsdump Not both.不是都。

dump (my preference): dump (我的偏好):

def create_json():
    with open("./data/student.txt", "w") as file:
        json.dump([ob.__dict__ for ob in stList], file)

OR dumps :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)

As a side note, in the future you'll want to watch out for scoping as you're using the global object stList .附带说明一下,将来您在使用全局 object stList时需要注意范围

You are encoding your dictionary to JSON string twice.您将字典编码为 JSON 字符串两次。 First you do this here:首先,您在这里执行此操作:

json_string = json.dumps([ob.__dict__ for ob in stList])

and then once again, here:然后再一次,在这里:

json.dump(json_string, file)

Alter this line with file.write(json_string)file.write(json_string)改变这一行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM