使用xmltodict从python中的xml文件创建json文件
我正在尝试使用xmltodict从输入xml文件创建json文件,代码如下使用xmltodict从python中的xml文件创建json文件,python,xml,json,xmltodict,Python,Xml,Json,Xmltodict,我正在尝试使用xmltodict从输入xml文件创建json文件,代码如下 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 ) 最后一行告诉我以下错误 Traceback (most recent call last):
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 )
最后一行告诉我以下错误
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
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/_init__.py”,转储文件第182行
fp.write(块)
TypeError:必须是unicode,而不是str
我想我需要更改编码。我的初始xml文件似乎是ascii。你知道怎么做吗?
感谢
unicode
和str
是Python版本3之前的两种不同类型的对象。通过强制将值转换为unicode
对象(基本上也是字符串):
my_var = unicode(my_str)
您可以以二进制模式打开该文件
outfile = io.open(filename_json, 'wb')
这将允许
str
。谢谢您的回答。你认为我应该在哪里使用unicode
调用?只要看看你的代码,我会说是json.dump(unicode(o),outfile)
,但是你必须自己尝试:)我没有安装你的库,也没有运行OSX,但是错误会给你一个触发错误的精确行号;也许围绕这一行的代码会对您的问题有所帮助。哪一行给出了错误?json.dump(o,outfile)行