Search code examples
jsonpython-3.xdata-extraction

Writing data of a dictionary containing enum values to a JSON file using Python


I have an enum as shown below:

class University(Enum):
    STUDENT = 1
    PROFESSOR = 2

I have a dictionary named 'university_info' containing data as shown below:

[{<University.PROFESSOR: 2>: {'iD': 1234,
 'Name': 'John Samuel'
 'Phone': 7531670961,
 'City': 'Rochester'}},

 {<University.PROFESSOR: 2>: {'iD': 5678,
 'Name': 'Alisa Potter',
 'Phone': 8904124567,
 'City': 'Manhattan'}}]

I want to write this data into a JSON file. I am using the below code:

import json
fileName='test.json'
def writeToJSONFile(data):
    with open(fileName, 'a+') as fp:
        json.dump(data, fp)

then I am calling the function on the dictionary as:

writeToJSONFile(university_info)

it is giving me an error:

key <University.PROFESSOR: 2> is not a string

but when I am doing:

writeToJSONFile(str(university_info))

It is printing result correctly

May I know how can I print the result into JSON without converting it into str?


Solution

  • Plain JSON can only encode the following.

    • object (Python dict)
    • array (Python list)
    • string (Python str)
    • number (Python float or int)
    • "true" (Python True)
    • "false" (Python False)
    • "null" (Python None)

    That's it. You must define a custom encoder and decoder for other types, which will usually also involve encoding it as a plain JSON structure. For example, an Enum could be [string, number]. But the default implementation does not include that.