1

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?

2

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.