Generating json file from xml file in python using xmltodict

I am trying to create json file from input xml file using xmltodict with 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 will get 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 think I need to change the encoding. My initial xml file seems to be ascii. Any idea on how to make this work? Thanks to

+3
json python xml xmltodict


source to share


2 answers


You can open the file in binary mode

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

      



This will also allow str

.

+5


source to share


unicode

and str

are two different types of objects in Python prior to version 3. You can turn your value into an object unicode

(which is basically also a string) by forcing it:



my_var = unicode(my_str)

      

0


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics