Python脚本内容
# -*- coding: cp936 -*- import json print "aaa" d = {"a": 1, "c": 3, "b": 2} with open("test.json1", "w") as f: json.dump(d, f) with open("test.json1", "r") as f: d1 = json.load(f) print d1 print d1['a'] print d1["c"] print d1["b"] print d1.keys from xml.etree import ElementTree as et; import json #从xml文件读取结点 转换为json格式,并保存到文件中 print('read node from xmlfile, transfer them to json, and save into jsonFile:') root=et.parse("testXml.xml"); print "ddddd" f=open('test.json','a',encoding="utf8"); for each in root.getiterator("person"): tempDict=each.attrib for childNode in each.getchildren(): tempDict[childNode.tag]=childNode.text tempJson=json.dumps(tempDict,ensure_ascii=False) print(tempJson) f.write(tempJson+"\n"); f.close()
<?xml version="1.0" encoding="gb2312"?> <root> <person age="18"> <name>zs</name> <sex>male的</sex> </person> <person age="19" des="hello"> <name>ls</name> <sex>female</sex> </person> <person age="19" des="hello"> <name>ls</name> <sex>female</sex> </person> </root>
#从json文件中读取,并打印 print('read json from jsonfile:') for eachJson in open('testJson.json','r',encoding='utf8'): tempStr=json.loads(eachJson); print(tempStr)
xml内容(命名为testXml.xml)
<?xml version="1.0" encoding="gb2312"?> <root> <person age="18"> <name>zs</name> <sex>male的</sex> </person> <person age="19" des="hello"> <name>ls</name> <sex>female</sex> </person> <person age="19" des="hello"> <name>ls</name> <sex>female</sex> </person> </root>