3

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

smci
  • 32,567
  • 20
  • 113
  • 146
RockridgeKid
  • 145
  • 3
  • 11

2 Answers2

5

You can open the file in binary mode

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

This will allow str as well.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
0

unicode and str are two different types of objects in Python prior to version 3. You can turn your value into a unicode object (which is basically also a string) by coercing it:

my_var = unicode(my_str)
akaIDIOT
  • 9,171
  • 3
  • 27
  • 30
  • Thanks for your answer. Where do you think I should use the `unicode` call? – RockridgeKid Feb 06 '13 at 08:36
  • Just looking at your code I'd say as `json.dump(unicode(o), outfile)`, but you'll have to try that yourself :) – akaIDIOT Feb 06 '13 at 08:37
  • I don't have your libraries installed nor run OSX, but the error gives you a precise line number that triggers the error; maybe the code surrounding that line will shed some light on your issue. – akaIDIOT Feb 06 '13 at 08:47