Python JSON模組與JsonPath

資料提取之JSON與JsonPATH

JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式,它使得人們很容易的進行閱讀和編寫。同時也方便了機器進行解析和生成。適用於進行資料互動的場景,比如網站前臺與後臺之間的資料互動。

JSON和XML的比較可謂不相上下。

Python 2。7中自帶了JSON模組,直接import json就可以使用了。

官方文件:http://docs。python。org/library/json。html

Json線上解析網站:http://www。json。cn/#

JSON

json簡單說就是javascript中的物件和陣列,所以這兩種結構就是物件和陣列兩種結構,透過這兩種結構可以表示各種複雜的結構

物件:物件在js中表示為{ }括起來的內容,資料結構為 { key:value, key:value, … }的鍵值對的結構,在面向物件的語言中,key為物件的屬性,value為對應的屬性值,所以很容易理解,取值方法為 物件。key 獲取屬性值,這個屬性值的型別可以是數字、字串、陣列、物件這幾種。

陣列:陣列在js中是中括號[ ]括起來的內容,資料結構為 [“Python”, “javascript”, “C++”, …],取值方式和所有語言中一樣,使用索引獲取,欄位值的型別可以是 數字、字串、陣列、物件幾種。

import json

json模組提供了四個功能:dumps、dump、loads、load,用於字串 和 python資料型別間進行轉換。

1。 json。loads()

把Json格式字串解碼轉換成Python物件 從json到python的型別轉化對照如下:

Python JSON模組與JsonPath

# json_loads。pyimport jsonstrList = ‘[1, 2, 3, 4]’strDict = ‘{“city”: “北京”, “name”: “大貓”}’json。loads(strList)# [1, 2, 3, 4]json。loads(strDict) # json資料自動按Unicode儲存# {u‘city’: u‘\u5317\u4eac’, u‘name’: u‘\u5927\u732b’}

2. json.dumps()

實現python型別轉化為json字串,返回一個str物件 把一個Python物件編碼轉換成Json字串

從python原始型別向json型別的轉化對照如下:

Python JSON模組與JsonPath

# json_dumps。pyimport jsonimport chardetlistStr = [1, 2, 3, 4]tupleStr = (1, 2, 3, 4)dictStr = {“city”: “北京”, “name”: “大貓”}json。dumps(listStr)# ‘[1, 2, 3, 4]’json。dumps(tupleStr)# ‘[1, 2, 3, 4]’# 注意:json。dumps() 序列化時預設使用的ascii編碼# 新增引數 ensure_ascii=False 禁用ascii編碼,按utf-8編碼# chardet。detect()返回字典, 其中confidence是檢測精確度json。dumps(dictStr)# ‘{“city”: “\\u5317\\u4eac”, “name”: “\\u5927\\u5218”}’chardet。detect(json。dumps(dictStr))# {‘confidence’: 1。0, ‘encoding’: ‘ascii’}print json。dumps(dictStr, ensure_ascii=False)# {“city”: “北京”, “name”: “大劉”}chardet。detect(json。dumps(dictStr, ensure_ascii=False))# {‘confidence’: 0。99, ‘encoding’: ‘utf-8’}

chardet是一個非常優秀的編碼識別模組,可透過pip安裝

3。 json。dump()

將Python內建型別序列化為json物件後寫入檔案

# json_dump。pyimport jsonlistStr = [{“city”: “北京”}, {“name”: “大劉”}]json。dump(listStr, open(“listStr。json”,“w”), ensure_ascii=False)dictStr = {“city”: “北京”, “name”: “大劉”}json。dump(dictStr, open(“dictStr。json”,“w”), ensure_ascii=False)

4。 json。load()

讀取檔案中json形式的字串元素 轉化成python型別

# json_load。pyimport jsonstrList = json。load(open(“listStr。json”))print strList# [{u‘city’: u‘\u5317\u4eac’}, {u‘name’: u‘\u5927\u5218’}]strDict = json。load(open(“dictStr。json”))print strDict# {u‘city’: u‘\u5317\u4eac’, u‘name’: u‘\u5927\u5218’}

JsonPath(瞭解)

JsonPath 是一種資訊抽取類庫,是從JSON文件中抽取指定資訊的工具,提供多種語言實現版本,包括:Javascript, Python, PHP 和 Java。

JsonPath 對於 JSON 來說,相當於 XPATH 對於 XML。

下載地址:https://pypi。python。org/pypi/jsonpath

安裝方法:點選Download URL連結下載jsonpath,解壓之後執行python setup。py install

官方文件:http://goessner。net/articles/JsonPath

JsonPath與XPath語法對比:

Json結構清晰,可讀性高,複雜度低,非常容易匹配,下表中對應了XPath的用法。

Python JSON模組與JsonPath

示例:

我們以拉勾網城市JSON檔案 http://www。lagou。com/lbs/getAllCitySearchLabels。json 為例,獲取所有城市。

# jsonpath_lagou。pyimport requestsimport jsonpathimport jsonimport chardeturl = ‘http://www。lagou。com/lbs/getAllCitySearchLabels。json’response = equests。get(url)html = response。text# 把json格式字串轉換成python物件jsonobj = json。loads(html)# 從根節點開始,匹配name節點citylist = jsonpath。jsonpath(jsonobj,‘$。。name’)print citylistprint type(citylist)fp = open(‘city。json’,‘w’)content = json。dumps(citylist, ensure_ascii=False)print contentfp。write(content。encode(‘utf-8’))fp。close()