Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将对象列表写入JSON文件_Python_Json - Fatal编程技术网

Python 将对象列表写入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

作为家庭作业的一部分,我必须制作一个包含类对象的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 = 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的字符串。阅读。类似问题: