需求
将xml文件转换为json文件,在网上找了一圈,发现文件大了,还收费,我这暴脾气,自己写一个吧!
实现
安装必须的依赖库,我们需要安装json库,用于处理json文件
pip install json
再装一个处理将xml转换为字典类型的库
pip install xmltodict==0.12.0
我们找一个xml文件吧,随便找了一个rss的xml文件,它的内容如下,
注意哈,内容中包含中文,一不小心转换结果很容易出现乱码
<rss>
<channel>
<title>参考消息电子版</title>
<link>http://www.ckxx.info/</link>
<item>
<guid>http://www.ckxx.info/other1/201111/7-55584.html</guid>
<title>伊朗核问题临近最后摊牌</title>
<description>伊朗核问题临近最后摊牌</description>
<link>http://www.ckxx.info/other1/201111/7-55584.html</link>
<pubDate>2011-11-07</pubDate>
</item>
<item>
<guid>http://www.ckxx.info/other1/201111/7-55583.html</guid>
<title>日本天皇因病住院</title>
<author>http://www.ckxx.info</author>
<description>日本天皇因病住院</description>
<link>http://www.ckxx.info/other1/201111/7-55583.html</link>
</item>
</channel>
</rss>
直接上代码吧,创建一个converter.py的文件,代码很简单,加载xml文件,将xml转换为字典类型,再将字典类型转换为json字符串,然后写入一个新文件就大功告成了
# -*- coding: utf-8 -*-
import json
import xmltodict
# 主程序,执行入口
if __name__ == '__main__':
with open('input1.xml', encoding="UTF-8") as xml_file:
# 将xml文件转化为字典类型数据
parsed_data = xmltodict.parse(xml_file.read())
# 关闭文件流,其实 不关闭with也会帮你关闭
xml_file.close()
# 将字典类型转化为json格式的字符串
json_conversion = json.dumps(parsed_data, ensure_ascii=False)
# 将字符串写到文件中
with open('output.json', 'w', encoding="UTF-8") as json_file:
json_file.write(json_conversion)
json_file.close()
运行 python converter.py 就能得到转换后的output.csv文件,结果如下:
{
"rss": {
"channel": {
"title": "参考消息电子版",
"link": "http://www.ckxx.info/",
"item": [
{
"guid": "http://www.ckxx.info/other1/201111/7-55584.html",
"title": "伊朗核问题临近最后摊牌",
"description": "伊朗核问题临近最后摊牌",
"link": "http://www.ckxx.info/other1/201111/7-55584.html",
"pubDate": "2011-11-07"
},
{
"guid": "http://www.ckxx.info/other1/201111/7-55583.html",
"title": "日本天皇因病住院",
"author": "http://www.ckxx.info",
"description": "日本天皇因病住院",
"link": "http://www.ckxx.info/other1/201111/7-55583.html"
}
]
}
}
}
需要注意的点
1.读取xml文件的时候,如果里面包含中文,要指定编码格式
with open(‘input1.xml’, encoding=“UTF-8”) as xml_file
- 将字典类型转化为json格式的字符串,需要把ascii码自动识别给关闭,要不然会出现下面的结果
json_conversion = json.dumps(parsed_data, ensure_ascii=False)
3.将json字符串写入文件时候,需要指定编码,否则在中文的地方会出现乱码
with open(‘output.json’, ‘w’, encoding=“UTF-8”) as json_file
如果 对您有帮助,请关注或点赞我哈。
如果您也对python有兴趣,我这里有一本《python编程手册》,里面几乎囊括了python的方方面面(1000页),可以作为字典使用以备忘记知识点的时候进行查询。领取方式:在鄙人的共重号(python实例实战)里发送 “python学习手册“” 进行领取,还有每天的实战实例。您的支持是我最大的动力,感谢!