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)單來說就是JavaScript中的對(duì)象和數(shù)組,所以這兩種結(jié)構(gòu)就是對(duì)象和數(shù)組兩種結(jié)構(gòu),通過這兩種結(jié)構(gòu)可以表示各種復(fù)雜的結(jié)構(gòu)。
對(duì)象:對(duì)象在js中表示為{ }括起來的內(nèi)容,數(shù)據(jù)結(jié)構(gòu)為{key1: value1, key2:value2, ...}的鍵值對(duì)的結(jié)構(gòu),在面向?qū)ο蟮恼Z言中,key為對(duì)象的屬性,value為對(duì)應(yīng)的屬性值,所以很容易理解,取值方法為 對(duì)象.key 獲取屬性值,這個(gè)屬性值的類型可以是數(shù)字、字符串、數(shù)組、對(duì)象。
數(shù)組:數(shù)組在js中是[ ]括起來的內(nèi)容,數(shù)據(jù)結(jié)構(gòu)為['Python', ‘JavaScript', 'C++', ...],取值方式和所有語言一樣,使用索引獲取,字段值的類型可以是數(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 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格式字符串解碼轉(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 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文檔中抽取指定信息的工具,提供多種語言實(shí)現(xiàn)版本,包括:JavaScript、Python、PHP和Java。
JsonPath對(duì)于JSON來說,相當(dāng)于XPATH對(duì)于XML。
下載地址:https://pypi.python.org/pypi/jsonpath
安裝方法:下載后解壓之后執(zhí)行 python setup.py install
官方文檔:http://goessner.net/articles/JsonPath
JsonPath與XPath語法對(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ù)屬性訪問,JsonPath不支持 |
| [] | [] | 迭代器(可以在里邊做簡(jiǎn)單的迭代操作,如數(shù)組下標(biāo),根據(jù)內(nèi)容選值等) |
| | | [,] | 支持迭代器中做多選 |
| [] | ?() | 支持過濾操作 |
| 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.request
import json
import 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-Agent
request = urllib.request.Request(url, headers = header)
# 向服務(wù)器發(fā)送這個(gè)請(qǐng)求
response = urllib.request.urlopen(request)
# 獲取頁面內(nèi)容:bytes
html = response.read()
# 轉(zhuǎn)碼:bytes轉(zhuǎn)str
html = 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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
用python 實(shí)現(xiàn)在不確定行數(shù)情況下多行輸入方法
今天小編就為大家分享一篇用python 實(shí)現(xiàn)在不確定行數(shù)情況下多行輸入方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01
python 讀取excel文件生成sql文件實(shí)例詳解
這篇文章主要介紹了python 讀取excel文件生成sql文件實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-05-05
Python?Flask?實(shí)現(xiàn)?HTML?文件壓縮案例代碼(9?級(jí)壓縮)
這篇文章主要介紹了Python?Flask?實(shí)現(xiàn)?HTML?文件壓縮案例代碼(9?級(jí)壓縮),本案例是基于?Python?Flask?進(jìn)行搭建,所以需要提前搭建一個(gè)?Flask?項(xiàng)目環(huán)境,有?app.py?文件和?templates/index.html?文件即可,需要的朋友可以參考下2023-01-01
基于Python實(shí)現(xiàn)給喜歡的主播自動(dòng)發(fā)彈幕
這篇文章主要介紹了python如何實(shí)現(xiàn)給喜歡的主播自動(dòng)發(fā)彈幕的功能,文中的示例代碼對(duì)我們學(xué)習(xí)Python有一定的幫助,感興趣的朋友可以了解下2021-12-12
python使用正則表達(dá)式檢測(cè)密碼強(qiáng)度源碼分享
客戶系統(tǒng)升級(jí),要求用戶密碼符合一定的規(guī)則,即:包含大小寫字母、數(shù)字、符號(hào),長(zhǎng)度不小于8,于是先用python寫了個(gè)簡(jiǎn)單的測(cè)試程序:2014-06-06
Python中處理unchecked未捕獲異常實(shí)例
這篇文章主要介紹了Python中處理unchecked未捕獲異常實(shí)例,本文講解使用回調(diào)或者是鉤子來處理unchecked異常,需要的朋友可以參考下2015-01-01

