[英]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 我试图使用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 )
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.
我的初始xml文件似乎是ascii。 Any idea on how to make this work?
有关如何使这项工作的任何想法? Thanks
谢谢
You can open the file in binary mode 您可以以二进制模式打开文件
outfile = io.open(filename_json, 'wb')
This will allow str
as well. 这也将允许
str
。
unicode
和str
是版本3之前的Python中的两种不同类型的对象。您可以通过强制它将您的值转换为unicode
对象(基本上也是一个字符串):
my_var = unicode(my_str)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.