0

I have a dictionary called job_highlight_dict which contains {job_id, JobHighlight}

job_id is number and JobHighlight is a type as defined below:

class JobHighlight:
    def __init__(self, display_salary, location, category):
        self.display_salary = display_salary
        self.location = location
        self.category = category

I want to convert job_highlight_dict to xml and write it to disk, this is what I have tried:

xml = dicttoxml.dicttoxml(self.job_highlight_dict)
file = open("export/path_%(time)s.xml", "wb")
file.write(xml)
file.close()

but I am getting the following error:

TypeError: Unsupported data type: <JobHighlight object at 0x000002D00FA48E88> (JobHighlight)

Hooman Bahreini
  • 14,480
  • 11
  • 70
  • 137

1 Answers1

1

You convert the job_highlight_dict["JobHighlight"] from a JobHighlight type to a dictionary.

Code

job_highlight_dict["JobHighlight"] = {
    "display_salary": job_highlight_dict["JobHighlight"].display_salary,
    "location": job_highlight_dict["JobHighlight"].location,
    "category": job_highlight_dict["JobHighlight"].category
}
xml = dicttoxml.dicttoxml(job_highlight_dict)
file = open("paths.xml", "wb")
file.write(xml)
file.close()

Or more simply:

job_highlight_dict["JobHighlight"] = vars(job_highlight_dict["JobHighlight"])
xml = dicttoxml.dicttoxml(job_highlight_dict)
file = open("paths.xml", "wb")
file.write(xml)
file.close()

See: Python dictionary from an object's fields

Example of Output

I formatted this, but in the file the xml will appear all on one line. If you want it formatted, you'll have to use pretty-printing or something of the like. See: https://pypi.org/project/dicttoxml/

<?xml version="1.0" encoding="UTF-8" ?>
<root>
    <job_id type="int">2</job_id>
    <JobHighlight type="dict">
        <display_salary type="str">$80k</display_salary>
        <location type="str">Los Angeles</location>
        <category type="str">Other</category>
    </JobHighlight>
</root>
zmike
  • 1,090
  • 10
  • 24