Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a json file from a xml file in python with xmltodict

I am trying to create a json file from an input xml file using xmltodict with the following code

import io, xmltodict, json
infile = io.open(filename_xml, 'r')
outfile = io.open(filename_json, 'w')
o = xmltodict.parse( infile.read() )
json.dump( o , outfile )

the last line get me the following error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 182, in dump
    fp.write(chunk)
TypeError: must be unicode, not str

I guess I need to change the encoding. My initial xml file seems to be ascii. Any idea on how to make this work? Thanks

like image 958
RockridgeKid Avatar asked Nov 17 '25 21:11

RockridgeKid


1 Answers

You can open the file in binary mode

outfile = io.open(filename_json, 'wb')

This will allow str as well.

like image 113
Olaf Dietsche Avatar answered Nov 19 '25 11:11

Olaf Dietsche