活動地址: 21天學習挑戰賽.
JSON(全名:JavaScript Object Notation 對象表示法)是一種輕量級的文本數據交換格式。
- JSON獨立於語言
- JSON具有自我描述性,更易理解
- JSON比XML更小,更快,更易解析
- 爬蟲經常會獲取接口數據,一般都是JSON格式。
{key1:value1, key2:value2…}
# 格式1:JSON 對象
{
"name": "admin", "age": 18}
# 格式2:JSON 數組
{
"student":
[
{
"name": "小明", "age": 18},
{
"name": "小紅", "age": 16},
{
"name": "小黑", "age": 20}
]
}
1、使用jsON字符串生成python對象(load)
2、由python對象格式化成為ison字符串(dump)
python transfor json
json transforpython
json.dumps(obj)
將python數據類型轉換為json格式的字符串。json.dump(obj, fp)
將python數據類型轉換並保存到son格式的文件內。json.loads(s)
將json格式的字符串轉換為python的類型。json.load(fp)
從json格式的文件中讀取數據並轉換為python的類型。
- json.dumps(obj)
語法格式:json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
sort_keys
:是否排序indent
:定義縮進距離separators
:是一個元組,定義分隔符的類型skipkeys
:是否允許JSON字串編碼字典對象時,字典的key不是字符串類型(默認是不允許)
>>> import json
# Python字典
>>> person = {
"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}
>>> print(person)
{
'name': '小明', 'age': 30, 'tel': ['888888', '1351111111'], 'isonly': True}
>>> type(person)
<class 'dict'
# Python字典轉換為json字符串
>>> jsonStr = json.dumps(person)
>>> print(jsonStr )
{
"name": "\u5c0f\u660e", "age": 30, "tel": ["888888", "1351111111"], "isonly": true}
>>> type(jsonStr)
<class 'str'>
// 將內容寫入json file
import json
person = {
"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}
jsonStr = json.dumps(person)
with open('test.json', 'w', encoding='utf-8') as f: # 打開文件
f.write(jsonStr) # 在文件裡寫入轉成的json串
- json.dump(obj,fp)
語法格式:json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
sort_keys
:是否排序indent
:定義縮進距離separators
:是一個元組,定義分隔符的類型skipkeys
:是否允許JSON字串編碼字典對象時,字典的key不是字符串類型(默認是不允許)
import json
person = {
"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}
json.dump(person, open('data.json', 'w'))
import json
person = {
"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}
json.dump(person, open('data.json', 'w'), sort_keys=True, indent=4, separators=(',', ': '))
- json.loads(s)
語法格式:json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
>>> import json
# Python字典
>>> person = {
"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}
>>> print(person)
{
'name': '小明', 'age': 30, 'tel': ['888888', '1351111111'], 'isonly': True}
>>> type(person)
<class 'dict'
# Python字典轉換為json字符串
>>> jsonStr = json.dumps(person)
>>> print(jsonStr )
{
"name": "\u5c0f\u660e", "age": 30, "tel": ["888888", "1351111111"], "isonly": true}
>>> type(jsonStr)
<class 'str'>
# json字符串再轉換為Python字典
>>> python_obj = json.loads(jsonStr)
>>> print(python_obj)
{
'name': '小明', 'age': 30, 'tel': ['888888', '1351111111'], 'isonly': True}
>>> print(type(python_obj))
<class 'dict'>
# 打印字典的所有key
>>> print(python_obj.keys())
dict_keys(['name', 'age', 'tel', 'isonly'])
# 打印字典的所有values
>>> print(python_obj.values())
dict_values(['小明', 30, ['888888', '1351111111'], True])
import json
f = open('data.json', encoding='utf-8')
content = f.read() # 使用loads()方法需要先讀文件
python_obj = json.loads(content)
print(python_obj)
- json.load(fp)
語法格式:json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
import json
python_obj = json.load(open('data.json','r'))
print(python_obj)
print(type(python_obj))
總結: 不管是dump還是load,帶s的都是和字符串相關的,不帶s的都是和文件相關的
pip install xmltodict
xml transfor json
import json
import xmltodict
def xml_to_json(xml_str):
"""parse是的xml解析器,參數需要
:param xml_str: xml字符串
:return: json字符串
"""
xml_parse = xmltodict.parse(xml_str)
# json庫dumps()是將dict轉化成json格式,loads()是將json轉化成dict格式。
# dumps()方法的ident=1,格式化json
json_str = json.dumps(xml_parse, indent=1)
return json_str
XML_PATH = './1.xml' # xml文件的路徑
with open(XML_PATH, 'r') as f:
xmlfile = f.read()
with open(XML_PATH[:-3] + 'json', 'w') as newfile:
newfile.write(xml_to_json(xmlfile))
json transfor xml
import xmltodict
import json
def json_to_xml(python_dict):
"""xmltodict庫的unparse()json轉xml
:param python_dict: python的字典對象
:return: xml字符串
"""
xml_str = xmltodict.unparse(python_dict)
return xml_str
JSON_PATH = './test.json' # json文件的路徑
with open(JSON_PATH, 'r') as f:
jsonfile = f.read()
python_dict = json.loads(jsonfile) # 將json字符串轉換為python字典對象
with open(JSON_PATH[:-4] + 'xml', 'w') as newfile:
newfile.write(json_to_xml(python_dict))
import json
json_str = '{"name":"test", "type":{"name":"seq", "parameter":["1", "2"]}}'
print(json_str)
print(type(json_str))
print('-' * 20)
# 1、JSON文件轉換為Python對象
python_obj = json.loads(json_str)
print(python_obj)
print(type(python_obj))
print('-' * 20)
# 2、定位具體的數據節點
print(python_obj.keys())
print(python_obj.values())
print(python_obj["name"])
print(python_obj["type"]["name"])
print(python_obj["type"]["parameter"][0])
print(python_obj["type"]["parameter"][1])
{
"student": {
"course": {
"name": "math",
"score": "90"
},
"info": {
"sex": "male",
"name": "name"
},
"stid": "10213"
}
}
```javascript
import json
# 1、JSON文件轉換為Python對象
python_obj = json.load(open('test.json', 'r'))
print(python_obj)
print(type(python_obj))
print("-" * 20)
# 2、解析json文件
# 輸出cours節點e下的數據
print(python_obj['student']['course']['name']) # 輸出name
print(python_obj['student']['course']['score']) # 輸出score
# 輸出info節點下的數據
print(python_obj['student']['info']['sex']) # 輸出sex
print(python_obj['student']['info']['name']) # 輸出name
# 輸出stid節點下的數據
print(python_obj['student']['stid']) # 輸出stid