活動地址:CSDN21天學習挑戰賽
目錄
1. JSON簡介
2. JSON語法格式
3. python中的json模塊
3.1 python數據類型與json數據類型轉換
3.2 json模塊常用函數
3.2.1 json.dumps()函數 python -> json
3.2.2 json.dump()函數 python -> json 並保存到文件中
3.2.3 json.loads() json -> python
3.2.4 json.load() 讀取json文件並轉換為python
3.3 解析JSONstring or file
**
**
JSON,Java Script Object Notation,是一種輕量級的文本數據交換格式,JSON獨立於語言,具有自我描述性,更易理解;JSON比XML更小、更快、更易解析;The interface data that crawlers often obtain isJSON格式.
JSON數據格式類似python的字典格式,It contains arrays enclosed in square brackets,類似python裡的列表.
語法格式:{key1:value1, key2:value2},如果valueThere are many data represented,用方括號括起來[],稱為數組.
JSONIt is composed of key-value pairs,The key part must be enclosed in double quotes "",值的部分,不允許出現函數function,undefined,NaN,但可以有null,不允許出現沒有意義的逗號.
如下:
格式1:JSON 對象
{
"name" : "Jack",
"age" : 18
}
格式2:JSON數組
{
"student":
[
{"name" : "Jack", "age" : 18},
{"name" : "Lucy", "age" : 18}
],
"classroom" : {
"class1" : "room1",
"class2" : "room2"
}
}
python提供了json模塊,作用是使用JSON字符串生成python對象(load),或由python對象格式化成json字符串(dump).
You need to import the module when using it:import json
python -> json時,Data types will vary,如下:
PythonJSONdictobjectlist,tuplearraystrstringint,float,int-&,float-derived EnumsnumberTruetrueFalsefalseNonenulljson -> python,The data type changes during conversion as follows:
JSONPythonobjectdictarrayliststringstrnumber(int)intnumber(real)floattrueTruefalseFalsenullNonejson.dumps()函數將python數據類型轉換為json格式的字符串.
json.dumps(obj,*,
skipkeys=False, # 是否允許JSON字串編碼字典對象時,字典的key不是字符串類型(默認不允許)
ensure_ascii=True,
check_circular=True,
allow_nan=True,
cls=None,
indent=None, # 定義縮進
separators=None, # 是一個元組,定義分隔符的類型
default=None,
sort_keys=False, # 是否排序
**kw)
使用示例1:將python字典轉換為json字符串
import json
# python 字典
p_persopn = {"name":"jack",
"age":18 ,
"tel":["666888",'12312341234'],
"isOnly":True
}
print("python: ",p_persopn)
# 轉換為json字符串
j_person = json.dumps(p_persopn)
print("JSON: ",j_person)
顯示結果:
python: {'name': 'jack', 'age': 18, 'tel': ['666888', '12312341234'], 'isOnly': True}
python <class 'dict'>
JSON: {"name": "jack", "age": 18, "tel": ["666888", "12312341234"], "isOnly": true}
JSON <class 'str'>
從結果中可以看出,pythonSingle quotes are printed,數據類型是字典,True首字母大寫;jsonDouble quotes are printed,數據類型是字符串,true全部小寫.
使用示例2:格式化輸出json字串:
import json
# python 字典
p_persopn = {"name":"jack",
"age":18 ,
"tel":["666888",'12312341234'],
"isOnly":True
}
print("python: ",p_persopn)
# 格式化輸出json字串
j_person = json.dumps(p_persopn,sort_keys=True,indent=4,separators=(',',':'))
print("格式化輸出JSON:",j_person)
j_person = json.dumps(p_persopn,sort_keys=True,indent=4,separators=('!','='))
print("格式化輸出JSON:",j_person)
顯示結果:
python: {'name': 'jack', 'age': 18, 'tel': ['666888', '12312341234'], 'isOnly': True}
格式化輸出JSON: {
"age":18,
"isOnly":true,
"name":"jack",
"tel":[
"666888",
"12312341234"
]
}
格式化輸出JSON: {
"age"=18!
"isOnly"=true!
"name"="jack"!
"tel"=[
"666888"!
"12312341234"
]
}
The definition can be seenseparators元組的第一個元素是jsonThe separator between each key-value pair in ,The second element of the tuple is jsonThe separator between key-value pairs.
使用示例3:將python字串轉換為jsonAfter the string is stored in the file
import json
# 保存json文件
p_persopn = {"name":"jack",
"age":18 ,
"tel":["666888",'12312341234'],
"isOnly":True
}
print("python: ",p_persopn)
j_person = json.dumps(p_persopn)
with open('test.json','w',encoding='utf-8') as f: # 打開文件
f.write(j_person) # 寫入文件
print("保存json文件完成!")
j_person = json.dumps(p_persopn,sort_keys=True,indent=4,separators=(',',':'))
with open('test_format.json','w',encoding='utf-8') as f: # 打開文件
f.write(j_person) # 寫入文件
print("保存json文件完成!")
顯示結果,新生成的文件:
json.dump()函數:
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
)
使用示例1:python格式轉換為jsonformat and save to file
import json
# python -> json 並保存文件
p_persopn = {"name":"jack",
"age":18 ,
"tel":["666888",'12312341234'],
"isOnly":True
}
json.dump(p_persopn,open("data.json","w"))
# 格式化保存python轉換的json
json.dump(p_persopn,open("data_format.json","w"),sort_keys=True,indent=4,separators=(',',':'))
The generated file is displayed:
json.dumps()和json.dump()比較:
語法格式:
json.loads(s,*,
cls=None,
object_hook=None,
parse_float=None,
parse_int=None,
parse_constant=None,
object_pairs_hook=None,
**kw
)
使用示例1:json轉換為python
# 將json轉換為python
p_persopn = {"name":"jack",
"age":18 ,
"tel":["666888",'12312341234'],
"isOnly":True
}
j_person = json.dumps(p_persopn)
# json 轉換為 python
new_python = json.loads(j_person)
print("json -> python:",new_python)
print(type(new_python))
顯示結果:
json -> python: {'name': 'jack', 'age': 18, 'tel': ['666888', '12312341234'], 'isOnly': True}
<class 'dict'>
使用示例2:讀取json文件並轉換成python
f = open("data.json",encoding='utf-8')
content = f.read()
python_obj = json.loads(content)
print(python_obj)
print(type(python_obj))
顯示結果:
{'name': 'jack', 'age': 18, 'tel': ['666888', '12312341234'], 'isOnly': True}
<class 'dict'>
json.load()從json格式的文件中讀取數據並轉換為python的類型.
語法格式:
json.load(fp,*,
cls=None,
object_hook==None,
parse_float==None,
parse_int=None,
parse_constant=None,
object_hook=None,
**kw
)
使用示例1:使用函數json.load()Read data from a file and convert topython的類型
import json
# 使用json.load()從json格式的文件中讀取數據並轉換為python的類型
python_obj = json.load(open('data.json','r'))
print('json.load(): ',python_obj)
print(type(python_obj))
顯示結果:
json.load(): {'name': 'jack', 'age': 18, 'tel': ['666888', '12312341234'], 'isOnly': True}
<class 'dict'>
json.load()和json.loads()區別:
分析:不管是JSONStrings are also files,都需要先把JSON格式的內容轉換為python對象,Then output layer by layerpython對象(如果轉換後的pythonObjects are multi-layered words).
示例代碼1:解析 json 字串
import json
json_str = '{"name":"test","type":{"name":"seq","parameter":["1","2"]}}'
print(json_str)
print(type(json_str))
print("="*70)
# 1. json文件轉換為python對象
p_obj = json.loads(json_str)
print(p_obj)
print(type(p_obj))
print("="*70)
# 2. Query a specific data node
print(p_obj.keys())
print(p_obj.values())
print("="*60)
print("輸出解析後的json文件")
print("name : ",p_obj["name"])
print("type : ",p_obj["type"])
print("type-name : ",p_obj["type"]["name"])
print("type-parameter : ",p_obj["type"]["parameter"])
print("type-parameter[0]",p_obj["type"]["parameter"][0])
print("type-parameter[1]",p_obj["type"]["parameter"][1])
# Or implemented recursivelyJSON文件解析,Only the dictionary type of the output is parsed as follows
def parase_dict(dct):
'''
解析輸出json轉換後的python字典數據
'''
keys = dct.keys()
vals = dct.values()
for key in keys:
if isinstance(dct[key],dict):
print(key+" = ", dct[key])
parase_dict(dct[key])
else:
print(key+" = ",dct[key])
顯示結果:
dict_keys(['name', 'type'])
dict_values(['test', {'name': 'seq', 'parameter': ['1', '2']}])
============================================================
輸出解析後的json文件
name : test
type : {'name': 'seq', 'parameter': ['1', '2']}
type-name : seq
type-parameter : ['1', '2']
type-parameter[0] 1
type-parameter[1] 2
示例代碼2:解析JSON文件
import json
def parase_dict(dct):
'''
解析輸出json轉換後的python字典數據
'''
keys = dct.keys()
vals = dct.values()
for key in keys:
if isinstance(dct[key],dict):
print(key+" = ", dct[key])
parase_dict(dct[key])
else:
print(key+" = ",dct[key])
# 解析JSON文件
print("="*60)
p_obj = json.load(open("test.json","r"))
print(p_obj)
parase_dict(p_obj)
顯示結果:
============================================================
{'name': 'jack', 'age': 18, 'tel': ['666888', '12312341234'], 'isOnly': True}
name = jack
age = 18
tel = ['666888', '12312341234']
isOnly = True
This article was first publish
Catalog Preface Why write co