Python json模塊與jsonpath模塊區(qū)別詳解
JSON(JavaScript Object Notation)是一種輕量級(jí)的數(shù)據(jù)交換格式,它使得人們很容易的進(jìn)行閱讀和編寫。同時(shí)也方便了機(jī)器進(jìn)行解析和生成。適用于進(jìn)行數(shù)據(jù)交互的場(chǎng)景,比如網(wǎng)站前臺(tái)與后臺(tái)之間的數(shù)據(jù)交互。
JSON和XML相比較可謂不相上下。
Python 3.X中自帶了JSON模塊,直接import json就可以使用了。
官方文檔:http://docs.python.org/library/json.html
Json在線解析網(wǎng)站:http://www.json.cn/
JSON
json簡(jiǎn)單來(lái)說(shuō)就是JavaScript中的對(duì)象和數(shù)組,所以這兩種結(jié)構(gòu)就是對(duì)象和數(shù)組兩種結(jié)構(gòu),通過(guò)這兩種結(jié)構(gòu)可以表示各種復(fù)雜的結(jié)構(gòu)。
對(duì)象:對(duì)象在js中表示為{ }括起來(lái)的內(nèi)容,數(shù)據(jù)結(jié)構(gòu)為{key1: value1, key2:value2, ...}的鍵值對(duì)的結(jié)構(gòu),在面向?qū)ο蟮恼Z(yǔ)言中,key為對(duì)象的屬性,value為對(duì)應(yīng)的屬性值,所以很容易理解,取值方法為 對(duì)象.key 獲取屬性值,這個(gè)屬性值的類型可以是數(shù)字、字符串、數(shù)組、對(duì)象。
數(shù)組:數(shù)組在js中是[ ]括起來(lái)的內(nèi)容,數(shù)據(jù)結(jié)構(gòu)為[’Python’, ‘JavaScript’, ’C++’, ...],取值方式和所有語(yǔ)言一樣,使用索引獲取,字段值的類型可以是數(shù)字、字符串、數(shù)組、對(duì)象。
json模塊
json模塊提供了四個(gè)功能:dumps、dump、loads、load,用于字符串和Python數(shù)據(jù)類型間進(jìn)行轉(zhuǎn)換。
1.json.dumps()
實(shí)現(xiàn)Python類型轉(zhuǎn)化為Json字符串,返回一個(gè)str對(duì)象,從Python到Json的類型轉(zhuǎn)換對(duì)照如下:
Python Json dict object list, tuple array str, utf-8 string int, float number True true False false None null
#!/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() 序列化時(shí)默認(rèn)使用的ascii編碼# 添加參數(shù) 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內(nèi)置類型序列化為Json對(duì)象后寫入文件
#!/usr/bin/python3# -*- coding:utf-8 -*-__author__ = ’mayi’import jsonlistStr = [{'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格式字符串解碼轉(zhuǎn)換成Python對(duì)象,從Json到Python的類型轉(zhuǎn)換對(duì)照如下:
Json Python object dict array list string utf-8 number(int) int number(real) float true True false False null None
#!/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數(shù)據(jù)自動(dòng)按utf-8存儲(chǔ)print(json.loads(strDict))# {’city’: ’北京’, ’name’: ’螞蟻’}
4.json.load()
讀取文件中Json形式的字符串,轉(zhuǎn)換成Python類型
#!/usr/bin/python3# -*- coding:utf-8 -*-__author__ = ’mayi’import jsonstrList = 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是一種信息抽取類庫(kù),是從JSON文檔中抽取指定信息的工具,提供多種語(yǔ)言實(shí)現(xiàn)版本,包括:JavaScript、Python、PHP和Java。
JsonPath對(duì)于JSON來(lái)說(shuō),相當(dāng)于XPATH對(duì)于XML。
下載地址:https://pypi.python.org/pypi/jsonpath
安裝方法:下載后解壓之后執(zhí)行 python setup.py install
官方文檔:http://goessner.net/articles/JsonPath
JsonPath與XPath語(yǔ)法對(duì)比:
JsonPath結(jié)構(gòu)清晰,可讀性高,復(fù)雜度低,非常容易匹配,下表中對(duì)應(yīng)了XPath的用法。
Xpath JSONPath 描述 / $ 根節(jié)點(diǎn) . @ 現(xiàn)行節(jié)點(diǎn) / . or [] 取子節(jié)點(diǎn) .. n/a 取父節(jié)點(diǎn),Jsonpath未支持 // .. 不管位置,選擇所有符合條件的節(jié)點(diǎn) * * 匹配所有元素節(jié)點(diǎn) @ n/a 根據(jù)屬性訪問(wèn),JsonPath不支持 [] [] 迭代器(可以在里邊做簡(jiǎn)單的迭代操作,如數(shù)組下標(biāo),根據(jù)內(nèi)容選值等) | [,] 支持迭代器中做多選 [] ?() 支持過(guò)濾操作 n/a () 支持表達(dá)式計(jì)算 () n/a 分組,JsonPath不支持
示例:
以拉勾網(wǎng)城市JSON文件:http://www.lagou.com/lbs/getAllCitySearchLabels.json 為例,獲取所有的城市名稱。
#!/usr/bin/python3# -*- coding:utf-8 -*-__author__ = ’mayi’ import urllib.requestimport jsonimport jsonpath # 拉勾網(wǎng)城市JSON文件url = ’http://www.lagou.com/lbs/getAllCitySearchLabels.json’# User-Agent頭header = {’User-Agent’:’Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36’} # url 連同 headers,一起構(gòu)造Request請(qǐng)求,這個(gè)請(qǐng)求將附帶 chrome 瀏覽器的User-Agentrequest = urllib.request.Request(url, headers = header) # 向服務(wù)器發(fā)送這個(gè)請(qǐng)求response = urllib.request.urlopen(request) # 獲取頁(yè)面內(nèi)容:byteshtml = response.read() # 轉(zhuǎn)碼:bytes轉(zhuǎn)strhtml = html.decode('utf-8') # 把json格式字符串轉(zhuǎn)換成python對(duì)象obj = json.loads(html) # 從根節(jié)點(diǎn)開始,匹配name節(jié)點(diǎn)city_list = jsonpath.jsonpath(obj, ’$..name’) # 打印獲取的name節(jié)點(diǎn)print(city_list)# 打印其類型print(type(city_list)) # 寫入本地磁盤文件with open('city.json', 'w', encoding = 'utf-8') as f: content = json.dumps(city_list, ensure_ascii = False) f.write(content)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 如何利用python操作注冊(cè)表2. vue3+ts+elementPLus實(shí)現(xiàn)v-preview指令3. Xml簡(jiǎn)介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理4. jsp文件下載功能實(shí)現(xiàn)代碼5. 詳解瀏覽器的緩存機(jī)制6. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享7. phpstudy apache開啟ssi使用詳解8. 如何在jsp界面中插入圖片9. xml中的空格之完全解說(shuō)10. JSP之表單提交get和post的區(qū)別詳解及實(shí)例
