JSON和JSONPATH
JSON(JavaScript Object Notation)是一種輕量級的資料交換格式,它使得人們很容易的進行閱讀和編寫。同時也方便了機器進行解析和生成。適用於進行資料互動的場景,比如網站前臺與後臺之間的資料互動。
JSON和XML相比較可謂不相上下。
Python 3.X中自帶了JSON模組,直接import json就可以使用了。
官方文件:http://docs.python.org/library/json.html
Json線上解析網站:http://www.json.cn/
一下內容參考自:https://www.jb51.net/article/182006.htm
JSON
json簡單來說就是JavaScript中的物件和陣列,所以這兩種結構就是物件和陣列兩種結構,通過這兩種結構可以表示各種複雜的結構。
物件:物件在js中表示為{ }括起來的內容,資料結構為{key1: value1, key2:value2, ...}的鍵值對的結構,在面向物件的語言中,key為物件的屬性,value為對應的屬性值,所以很容易理解,取值方法為 物件.key 獲取屬性值,這個屬性值的型別可以是數字、字串、陣列、物件。
陣列:陣列在js中是[ ]括起來的內容,資料結構為['Python', ‘JavaScript', 'C++', ...],取值方式和所有語言一樣,使用索引獲取,欄位值的型別可以是數字、字串、陣列、物件。
json模組
json模組提供了四個功能:dumps、dump、loads、load,用於字串和Python資料型別間進行轉換。
1.json.dumps()
實現Python型別轉化為Json字串,返回一個str物件,從Python到Json的型別轉換對照如
Python | Json |
dict | object |
list, tuple | array |
str, utf-8 | string |
int, float | number |
True | true |
False | false |
None | null |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#!/usr/bin/python3 # -*- coding:utf-8 -*-
__author__ = 'mayi'
import json
listStr = [ 1 , 2 , 3 , 4 ]
tupleStr = ( 1 , 2 , 3 , 4 )
dictStr = { "city" : "北京" , "name" : "螞蟻" }
print (json.dumps(listStr))
# [1, 2, 3, 4]
print ( type (json.dumps(listStr)))
# <class 'str'>
print (json.dumps(tupleStr))
# [1, 2, 3, 4]
print ( type (json.dumps(tupleStr)))
# <class 'str'>
# 注意:json.dumps() 序列化時預設使用的ascii編碼
# 新增引數 ensure_ascii=False 禁用ascii編碼,按utf-8編碼
print (json.dumps(dictStr, ensure_ascii = False ))
# {"city": "北京", "name": "螞蟻"}
print ( type (json.dumps(dictStr, ensure_ascii = False )))
# <class 'str'>
|
2.json.dump()
將Python內建型別序列化為Json物件後寫入檔案
1 2 3 4 5 6 7 8 9 |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
__author__ = 'mayi'
import json
listStr = [{ "city" : "北京" }, { "name" : "螞蟻" }]
json.dump(listStr, open ( "listStr.json" , "w" , encoding = "utf-8" ), ensure_ascii = False )
dictStr = { "city" : "北京" , "name" : "螞蟻" }
json.dump(dictStr, open ( "dictStr.json" , "w" , encoding = "utf-8" ), ensure_ascii = False )
|
3.json.loads()
把Json格式字串解碼轉換成Python物件,從Json到Python的型別轉換對照如下:
Json | Python |
object | dict |
array | list |
string | utf-8 |
number(int) | int |
number(real) | float |
true | True |
false | False |
null | None |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
__author__ = 'mayi'
import json
strList = '[1, 2, 3, 4]'
strDict = '{"city": "北京", "name": "螞蟻"}'
print (json.loads(strList))
# [1, 2, 3, 4]
# json資料自動按utf-8儲存
print (json.loads(strDict))
# {'city': '北京', 'name': '螞蟻'}
|
4.json.load()
讀取檔案中Json形式的字串,轉換成Python型別
1 2 3 4 5 6 7 8 9 10 11 |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
__author__ = 'mayi'
import json
strList = json.load( open ( "listStr.json" , "r" , encoding = "utf-8" ))
print (strList)
# [{'city': '北京'}, {'name': '螞蟻'}]
strDict = json.load( open ( "dictStr.json" , "r" , encoding = "utf-8" ))
print (strDict)
# {'city': '北京', 'name': '螞蟻'}
|
JsonPath
JsonPath是一種資訊抽取類庫,是從JSON文件中抽取指定資訊的工具,提供多種語言實現版本,包括:JavaScript、Python、PHP和Java。
JsonPath對於JSON來說,相當於XPATH對於XML。
下載地址:https://pypi.python.org/pypi/jsonpath
安裝方法:下載後解壓之後執行 python setup.py install
官方文件:http://goessner.net/articles/JsonPath
JsonPath與XPath語法對比:
JsonPath結構清晰,可讀性高,複雜度低,非常容易匹配,下表中對應了XPath的用法。
Xpath | JSONPath | 描述 |
/ | $ | 根節點 |
. | @ | 現行節點 |
/ | . or [] | 取子節點 |
.. | n/a | 取父節點,Jsonpath未支援 |
// | .. | 不管位置,選擇所有符合條件的節點 |
* | * | 匹配所有元素節點 |
@ | n/a | 根據屬性訪問,JsonPath不支援 |
[] | [] | 迭代器(可以在裡邊做簡單的迭代操作,如陣列下標,根據內容選值等) |
| | [,] | 支援迭代器中做多選 |
[] | ?() | 支援過濾操作 |
n/a | () | 支援表示式計算 |
() | n/a | 分組,JsonPath不支援 |
示例:
以拉勾網城市JSON檔案:http://www.lagou.com/lbs/getAllCitySearchLabels.json為例,獲取所有的城市名稱。
from urllib import request import json import jsonpath url = "http://www.lagou.com/lbs/getAllCitySearchLabels.json" headers = { "User-Agent": 'Mozilla/5.0 (compatible; U; ABrowse 0.6; Syllable) AppleWebKit/420+ (KHTML, like Gecko)' } req = request.Request(url=url,headers=headers) response = request.urlopen(req) html = response.read().decode("utf-8") #json字串格式轉化為python格式 obj = json.loads(html) #通過jsonpath提取出name屬性的值 city_list = jsonpath.jsonpath(obj,"$..name") #再將其轉化為json格式並寫入檔案city.json #ensure_ascii是指是否需要轉碼為ascii,選擇false會轉為unicode,方便後面轉嗎為utf-8 json.dump(city_list,open("city.json","w",encoding='utf-8'),ensure_ascii=False)