2020年12月9日 星期三

Python 上面常使用的資料格式:Json, XML 和 CSV

Python handle json

1. With http request :

resp = requests.post(....)

json_object = resp.json()

2. With string:

json_data = '{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}'

json_object = (json.loads(json_data))

3. With Json file :

with open('file.json', 'r') as f:

    json_object = json.load(f)

4. Check key exist :

if 'som_key' in json_object :

5. iterate :

for onekey on json_object:

or

for (index,key) in enumerate(json_object):

Python handle XML :
1. With string :

import xml.etree.ElementTree as ET
xml_str = '<a> <b attr="c"></b></a>'
root = ET.fromstring(r.content)

2. With http request :

resp = requests.get(...)
xml_str = resp.content
# Fall back to 1.

3. With XML file

tree = ET.parse('xmlfile.xml')
root = tree.getRoot()