2020-1-7(169)

1、 实现一次json和python对象的互转

>>> data_py={"a":97,2:(1,2),1:True,0:None,"d":{"a":1},"d":[1,2]}
>>> json.dumps(data_py)
'{"a": 97, "2": [1, 2], "1": true, "0": null, "d": [1, 2]}'
>>>
>>> data_js=json.dumps(data_py)
>>> json.loads(data_js)
{'a': 97, '2': [1, 2], '1': True, '0': None, 'd': [1, 2]}

2、 实现一个json串转化为xml文件,然后把xml文件的内容转化为一个python对象

from xml.dom.minidom import parse 
from xml.dom.minidom import Document
import json
import os

def json_to_xml(json_str,path):
    '''json串转化为xml文件'''
    try:
        data=json.loads(json_str)
        print(data)
    except:
        print("不是合法的json串") 
        
    doc=Document()
    database=doc.createElement("database") #创建根节点
    database.setAttribute("type","MySQL")  #创建节点属性
    doc.appendChild(database)
    info=doc.createElement("info")     #创建节点
    database.appendChild(info)
    for k,v in data.items():
        tag=doc.createElement(k)      #创建节点
        tag.appendChild(doc.createTextNode(v))   #创建节点文本
        info.appendChild(tag)
    with open(path,"w",encoding="utf-8") as fp:
        doc.writexml(fp,indent='',addindent='\t',newl='\n',encoding="utf-8")
        
    
json_to_xml('{"ip":"10.10.10.10","username":"cc","password":"123456"}',"d:\\2019\\mysql.xml")      

def xml_to_python(path):
    '''xml文件串转化为python字典对象'''
    if not os.path.exists(path):
        print("xml文件不存在")
    if os.path.splitext(path)[1]!=".xml":
        print("xml文件格式错误")
    result={}
    DOMTree=parse(path)
    database=DOMTree.documentElement  #获取根节点
    info=database.getElementsByTagName("info")
    for i in range(1,len(info[0].childNodes),2):
        key=info[0].childNodes[i].tagName
        value=info[0].childNodes[i].childNodes[0].data
        result[key]=value
    
    return result
    
print(xml_to_python("d:\\2019\\mysql.xml")) 
<?xml version="1.0" encoding="utf-8"?>
<database type="MySQL">
	<info>
		<ip>10.10.10.10</ip>
		<username>cc</username>
		<password>123456</password>
	</info>
</database>

解析movies.xml

<collection shelf="New Arrivals">
<movie title="Enemy Behind">
   <type>War, Thriller</type>
   <format>DVD</format>
   <year>2003</year>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Talk about a US-Japan war</description>
</movie>

<movie title="Transformers">
   <type>Anime, Science Fiction</type>
   <format>DVD</format>
   <year>1989</year>
   <rating>R</rating>
   <stars>8</stars>
   <description>A schientific fiction</description>
</movie>

<movie title="Trigun">
   <type>Anime, Action</type>
   <format>DVD</format>
   <episodes>4</episodes>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Vash the Stampede!</description>
</movie>

<movie title="Ishtar">
   <type>Comedy</type>
   <format>VHS</format>
   <rating>PG</rating>
   <stars>2</stars>
   <description>Viewable boredom</description>
</movie>
</collection>
from xml.dom.minidom import parse 
import json

class ParseXML:
    def __init__(self,path):
        self.DOMTree=parse(path)
        self.root=self.DOMTree.documentElement
    
    def get_tag_text(self):
        movie_tag={}  #movie的tag和对应的text
        result={}  #四个movie的tag和对应的text
        movies=self.root.getElementsByTagName("movie") #得到四个movie标签
        for i in range(len(movies)):
            key=movies[i].getAttribute("title") #movie的title
            #遍历movies下的节点,跳过换行节点
            for j in range(1,len(movies[i].childNodes),2): 
                #将movie下的节点,按照{标签:文本}格式存入字典
                movie_tag[(movies[i].childNodes)[j].tagName]\
                =(movies[i].childNodes)[j].childNodes[0].data
            #按照movie的{title:{标签:文本}}格式存入字典    
            result[key]=movie_tag
            movie_tag={} #清空{标签:文本}字典,空字典进行下一次循环
            
        return result

p=ParseXML("d:\\2019\\movies.xml")
data=p.get_tag_text()
print(json.dumps(data,indent=3))
>>> from xml.dom.minidom import parse
>>> DOMTree=parse("d:\\2019\\movies.xml")
>>> collection=DOMTree.documentElement
>>> collection.childNodes
[<DOM Text node "'\n'">, <DOM Element: movie at 0x173981cc548>, <DOM Text node "'\n'">, <DOM Element: movie at 0x1739834f368>, <DOM Text node "'\n   '">, <DOM Element: movie at 0x1739834f7c8>, <DOM Text node "'\n'">, <DOM Element: movie at 0x1739834fc28>, <DOM Text node "'\n'">]
>>> collection
<DOM Element: collection at 0x173981cc188>
>>> for movie in range(1,len(collection.childNodes),2):
...     print(movie)
...
1
3
5
7
>>> for movie in range(1,len(collection.childNodes),2):
...     print(collection.childNodes[movie])
...
<DOM Element: movie at 0x173981cc548>
<DOM Element: movie at 0x1739834f368>
<DOM Element: movie at 0x1739834f7c8>
<DOM Element: movie at 0x1739834fc28>
>>> collection.getElementsByTagName("type")
[<DOM Element: type at 0x173981ccf48>, <DOM Element: type at 0x1739834f408>, <DOM Element: type at 0x1739834f868>, <DOM Element: type at 0x1739834fcc8>]
>>> from xml.dom.minidom import parse
>>> DOMTree=parse("d:\\2019\\movies.xml")
>>> collection=DOMTree.documentElement
>>> collection
<DOM Element: collection at 0x17398359048>
>>> collection.getElementsByTagName("movie")
[<DOM Element: movie at 0x173983590e8>, <DOM Element: movie at 0x17398359548>, <DOM Element: movie at 0x173983599a8>, <DOM Element: movie at 0x17398359e08>]
>>> collection.childNodes
[<DOM Text node "'\n'">, <DOM Element: movie at 0x173983590e8>, <DOM Text node "'\n\n'">, <DOM Element: movie at 0x17398359548>, <DOM Text node "'\n\n'">, <DOM Element: movie at 0x173983599a8>, <DOM Text node "'\n\n'">, <DOM Element: movie at 0x17398359e08>, <DOM Text node "'\n'">]
>>> collection.childNodes[1].nodeType
1
>>> collection.childNodes[0].nodeType
3
>>> collection.childNodes[2].nodeType
3
>>> movies=collection.getElementsByTagName("movie")
>>> movies
[<DOM Element: movie at 0x173983590e8>, <DOM Element: movie at 0x17398359548>, <DOM Element: movie at 0x173983599a8>, <DOM Element: movie at 0x17398359e08>]
>>> movies[0].childNodes
[<DOM Text node "'\n   '">, <DOM Element: type at 0x17398359188>, <DOM Text node "'\n   '">, <DOM Element: format at 0x17398359228>, <DOM Text node "'\n   '">, <DOM Element: year at 0x173983592c8>, <DOM Text node "'\n   '">, <DOM Element: rating at 0x17398359368>, <DOM Text node "'\n   '">, <DOM Element: stars at 0x17398359408>, <DOM Text node "'\n   '">, <DOM Element: description at 0x173983594a8>, <DOM Text node "'\n'">]
>>> movies[0].getElementsByTagName("title")
[]
>>> movies[0].getElementsByTagName("type")
[<DOM Element: type at 0x17398359188>]
>>> movies[0].getElementsByTagName("fomat")
[]
>>> movies[0].getElementsByTagName("format")
[<DOM Element: format at 0x17398359228>]
>>> movies[0].getElementsByTagName("format")[0].childNodes
[<DOM Text node "'DVD'">]
>>> movies[0].getElementsByTagName("format")[0].childNodes
[<DOM Text node "'DVD'">]
>>> movies[0].getElementsByTagName("format")[0].childNodes[0].data
'DVD'
>>> collection.getElementsByTagName("movie")[0].getElementsByTagName("format")[0].childNodes[0].data
'DVD'
>>> collection.childNodes
[<DOM Text node "'\n'">, <DOM Element: movie at 0x173983590e8>, <DOM Text node "'\n\n'">, <DOM Element: movie at 0x17398359548>, <DOM Text node "'\n\n'">, <DOM Element: movie at 0x173983599a8>, <DOM Text node "'\n\n'">, <DOM Element: movie at 0x17398359e08>, <DOM Text node "'\n'">]
>>> collection.childNodes[1].childNodes
[<DOM Text node "'\n   '">, <DOM Element: type at 0x17398359188>, <DOM Text node "'\n   '">, <DOM Element: format at 0x17398359228>, <DOM Text node "'\n   '">, <DOM Element: year at 0x173983592c8>, <DOM Text node "'\n   '">, <DOM Element: rating at 0x17398359368>, <DOM Text node "'\n   '">, <DOM Element: stars at 0x17398359408>, <DOM Text node "'\n   '">, <DOM Element: description at 0x173983594a8>, <DOM Text node "'\n'">]
>>> collection.getElementsByTagName("movie")
[<DOM Element: movie at 0x173983590e8>, <DOM Element: movie at 0x17398359548>, <DOM Element: movie at 0x173983599a8>, <DOM Element: movie at 0x17398359e08>]
>>> collection.getElementsByTagName("movie")[0].getAttribute("title")
'Enemy Behind'
>>> collection.getElementsByTagName("movie")[1].getAttribute("title")
'Transformers'
>>> collection.childNode
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Element' object has no attribute 'childNode'
>>> collection.childNodes
[<DOM Text node "'\n'">, <DOM Element: movie at 0x173983590e8>, <DOM Text node "'\n\n'">, <DOM Element: movie at 0x17398359548>, <DOM Text node "'\n\n'">, <DOM Element: movie at 0x173983599a8>, <DOM Text node "'\n\n'">, <DOM Element: movie at 0x17398359e08>, <DOM Text node "'\n'">]


C:\Users\39621>python
Python 3.7.5 (tags/v3.7.5:5c02a39a0b, Oct 15 2019, 00:11:34) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from xml.dom.minidom import parse
>>> DOMTree=parse("d:\\2019\\movies.xml")
>>> root=DOMTree.documentElement
>>> root.childNodes
[<DOM Text node "'\n'">, <DOM Element: movie at 0x23ebbb6b548>, <DOM Text node "'\n\n'">, <DOM Element: movie at 0x23ebbcef368>, <DOM Text node "'\n\n'">, <DOM Element: movie at 0x23ebbcef7c8>, <DOM Text node "'\n\n'">, <DOM Element: movie at 0x23ebbcefc28>, <DOM Text node "'\n'">]
>>> root.childNodes[1].TagName
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Element' object has no attribute 'TagName'
>>> root.childNodes[1].childNode
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Element' object has no attribute 'childNode'
>>> root.childNodes[1].childNodes
[<DOM Text node "'\n   '">, <DOM Element: type at 0x23ebbb6bf48>, <DOM Text node "'\n   '">, <DOM Element: format at 0x23ebbcef048>, <DOM Text node "'\n   '">, <DOM Element: year at 0x23ebbcef0e8>, <DOM Text node "'\n   '">, <DOM Element: rating at 0x23ebbcef188>, <DOM Text node "'\n   '">, <DOM Element: stars at 0x23ebbcef228>, <DOM Text node "'\n   '">, <DOM Element: description at 0x23ebbcef2c8>, <DOM Text node "'\n'">]
>>> root.childNodes[1].childNodes.TagName
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NodeList' object has no attribute 'TagName'
>>> root.childNodes[1].childNodes[1].TagName
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Element' object has no attribute 'TagName'
>>> root.childNodes[1].childNodes[1].tagName
'type'
>>> root.childNodes[1].childNodes.tagName
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NodeList' object has no attribute 'tagName'
>>> root.childNodes[1].tagName
'movie'
>>> root.childNodes[3].tagName
'movie'
>>> root.tagName
'collection'
>>> movies=root.getElementsByTagName("movie")
>>> movies
[<DOM Element: movie at 0x23ebbb6b548>, <DOM Element: movie at 0x23ebbcef368>, <DOM Element: movie at 0x23ebbcef7c8>, <DOM Element: movie at 0x23ebbcefc28>]
>>> movies[0].childNodes
[<DOM Text node "'\n   '">, <DOM Element: type at 0x23ebbb6bf48>, <DOM Text node "'\n   '">, <DOM Element: format at 0x23ebbcef048>, <DOM Text node "'\n   '">, <DOM Element: year at 0x23ebbcef0e8>, <DOM Text node "'\n   '">, <DOM Element: rating at 0x23ebbcef188>, <DOM Text node "'\n   '">, <DOM Element: stars at 0x23ebbcef228>, <DOM Text node "'\n   '">, <DOM Element: description at 0x23ebbcef2c8>, <DOM Text node "'\n'">]



C:\Users\39621>python
Python 3.7.5 (tags/v3.7.5:5c02a39a0b, Oct 15 2019, 00:11:34) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> data_py={"a":97,2:"two",(1,2):[3,4],"b":2.2,"c":{5,6},"d":{"a":1,"b":2}}
>>> json.dumps(data_py)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\App\Python37\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "D:\App\Python37\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "D:\App\Python37\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
TypeError: keys must be str, int, float, bool or None, not tuple
>>> data_py={"a":97,2:"two",True:[3,4],None:0,"b":2.2,"c":{5,6},"d":{"a":1,"b":2}}
>>> data_py={"a":97,2:"two",True:[3,4],None:0,"c":{5,6},"d":{"a":1}}
>>> json.dumps(data_py)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\App\Python37\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "D:\App\Python37\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "D:\App\Python37\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "D:\App\Python37\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type set is not JSON serializable
>>> data_py={"a":97,2:"two",1:True,0:None,"c":{5,6},"d":{"a":1}}
>>> json.dumps(data_py)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\App\Python37\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "D:\App\Python37\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "D:\App\Python37\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "D:\App\Python37\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type set is not JSON serializable
>>> data_py={"a":97,2:"two","1":True,"0":None,"c":{5,6},"d":{"a":1}}
>>> json.dumps(data_py)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\App\Python37\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "D:\App\Python37\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "D:\App\Python37\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "D:\App\Python37\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type set is not JSON serializable
>>> data_py={"a":97,"2":"two","1":True,"0":None,"c":{5,6},"d":{"a":1}}
>>> json.dumps(data_py)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\App\Python37\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "D:\App\Python37\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "D:\App\Python37\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "D:\App\Python37\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type set is not JSON serializable
>>> data_py={"a":97,"2":"two","1":True,"0":None,"c":{5,6}}
>>> json.dumps(data_py)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\App\Python37\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "D:\App\Python37\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "D:\App\Python37\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "D:\App\Python37\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type set is not JSON serializable
>>> data_py={"a":97,"2":"two","1":True,"0":None}
>>> json.dumps(data_py)
'{"a": 97, "2": "two", "1": true, "0": null}'
>>> data_py={"a":97,"2":"two","1":True,"0":None,"c":{5,6}}
>>> json.dumps(data_py)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\App\Python37\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "D:\App\Python37\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "D:\App\Python37\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "D:\App\Python37\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type set is not JSON serializable
>>> data_py={"a":97,"2":"two","1":True,"0":None,"d":{"a":1}}
>>> json.dumps(data_py)
'{"a": 97, "2": "two", "1": true, "0": null, "d": {"a": 1}}'
>>> data_py={"a":97,"2":"two","1":True,0:None,"d":{"a":1}}
>>> json.dumps(data_py)
'{"a": 97, "2": "two", "1": true, "0": null, "d": {"a": 1}}'
>>> data_py={"a":97,2:"two",1:True,0:None,"d":{"a":1}}
>>> json.dumps(data_py)
'{"a": 97, "2": "two", "1": true, "0": null, "d": {"a": 1}}'
>>> data_py={"a":97,2:(1,2),1:True,0:None,"d":{"a":1},"d":[1,2]}
>>> json.dumps(data_py)
'{"a": 97, "2": [1, 2], "1": true, "0": null, "d": [1, 2]}'
>>> data_js=json.dumps(data_py)
>>> json.loads(data_js)
{'a': 97, '2': [1, 2], '1': True, '0': None, 'd': [1, 2]}
>>> data='{"ip":"10.10.10.10","username":"cc","password":"123456"}'
>>> type(data)
<class 'str'>

C:\Users\39621>python
Python 3.7.5 (tags/v3.7.5:5c02a39a0b, Oct 15 2019, 00:11:34) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from xml.dom.minidom import parse
>>> DOMTree=parse("d:\\2019\\mysql.xml")
>>> database=DOMTree.documentElement
>>> database
<DOM Element: database at 0x1f916ebb188>
>>> info=database.getElementsTagName("info")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Element' object has no attribute 'getElementsTagName'
>>> info=database.getElementsByTagName("info")
>>> info
[<DOM Element: info at 0x1f916ebb548>]
>>> info.childNodes
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NodeList' object has no attribute 'childNodes'
>>> info[0].childNodes
[<DOM Text node "'\n\t\t'">, <DOM Element: ip at 0x1f916ebbf48>, <DOM Text node "'\n\t\t'">, <DOM Element: username at 0x1f91703f048>, <DOM Text node "'\n\t\t'">, <DOM Element: password at 0x1f91703f0e8>, <DOM Text node "'\n\t'">]
>>> info[0].childNodes[1]
<DOM Element: ip at 0x1f916ebbf48>
>>> info[0].childNodes[1].tagName
'ip'
>>> info[0].childNodes[1].childNodes[0]
<DOM Text node "'10.10.10.1'...">
>>> info[0].childNodes[1].childNodes[0].data
'10.10.10.10'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值