Cerberus
Cerberus

Reputation: 51

Writing list of objects to JSON file

As part of my homework I have to make a JSON file with class objects in it. 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

Here is the output in student.txt:

 "[{\"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?

Upvotes: 1

Views: 14074

Answers (2)

r.ook
r.ook

Reputation: 13868

You should use either dumps, or dump. Not both.

dump (my preference):

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

OR 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.

Upvotes: 7

Maks Babarowski
Maks Babarowski

Reputation: 672

You are encoding your dictionary to JSON string twice. 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)

Upvotes: 1

Related Questions