Json與jsonpath再認識與初識
阿新 • • 發佈:2019-03-22
ren 切片 經營 arc als 信息抽取 lis n) code
一.json格式的數據
1.認識
JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式,
它使得人們很容易的進行閱讀和編寫。同時也方便了機器進行解析和生成。適用於
進行數據交互的場景,比如網站前臺與後臺之間的數據交互。
2.格式轉換
2.1 json.loads()
把Json格式字符串解碼轉換成Python對象,從json到python的類型轉化對照如下:
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
import json strList = ‘[1, 2, 3, 4]‘ strDict = ‘{"city": "北京", "name": "大貓"}‘ print(json.loads(strList)) print(json.loads(strDict))
2.2 json.dumps()
python類型轉化為json字符串,返回一個str對象把一個Python對象編碼轉換成Json字符串,
從python原始類型向json類型的轉化對照如下
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
import json listStr = [1, 2, 3, 4] tupleStr = (1, 2, 3, 4) dictStr = {"city": "北京", "name": "大貓"} print(json.dumps(listStr)) print(json.dumps(tupleStr)) # 註意:json.dumps() 序列化時默認使用的ascii編碼 # 添加參數 ensure_ascii=False 禁用ascii編碼,按utf-8編碼 print(json.dumps(dictStr)) print(json.dumps(dictStr, ensure_ascii=False)) ‘‘‘ 輸出結果: [1, 2, 3, 4] [1, 2, 3, 4] {"city": "\u5317\u4eac", "name": "\u5927\u732b"} {"city": "北京", "name": "大貓"} ‘‘‘
二、JsonPath簡介
JsonPath 是一種信息抽取類庫,是從JSON文檔中抽取指定信息的工具
1.jsonpath和xpath的對比
Json結構清晰,可讀性高,復雜度低,非常容易匹配,下表中對應了XPath的用法
XPath的 | JSONPath | 描述 |
/ | $ | 根對象/元素 |
。 | @ | 當前的對象/元素 |
/ | 。要麽 [] | 兒童經營者 |
.. | N / A | 父運營商 |
// | .. | 遞歸下降。JSONPath借用了E4X的這種語法。 |
* | * | 通配符。所有對象/元素無論其名稱如何。 |
@ | N / A | 屬性訪問。JSON結構沒有屬性。 |
[] | [] | 下標運算符。XPath使用它來叠代元素集合和謂詞。在Javascript和JSON中,它是本機數組運算符。 |
| | [,] | XPath中的Union運算符導致節點集的組合。JSONPath允許使用備用名稱或數組索引作為集合。 |
N / A | [開始:結束:步驟] | 從ES4借來的數組切片運算符。 |
[] | ?() | 應用過濾器(腳本)表達式。 |
N / A | () | 腳本表達式,使用底層腳本引擎。 |
() | N / A | 在Xpath中分組 |
2.實例
from urllib import request import jsonpath import json url = ‘http://www.lagou.com/lbs/getAllCitySearchLabels.json‘ req =request.Request(url) response = request.urlopen(req) html = response.read() # 把json格式字符串轉換成python對象 jsonobj = json.loads(html) # 從根節點開始,匹配根節點下面所有的name節點 citylist = jsonpath.jsonpath(jsonobj,‘$..name‘) print(citylist) print(type(citylist)) fp = open(‘city.json‘,‘w‘) content = json.dumps(citylist, ensure_ascii=False) print(content) fp.write(content.encode("utf-8").decode("utf-8")) fp.close()
三、字符串編碼轉換
# 1. 因為Python3默認字符串是unicode格式 unicodeStr = "你好地球" print(unicodeStr) # 2. 再將 Unicode 編碼格式字符串 轉換成 GBK 編碼 gbkData = unicodeStr.encode("GBK") print(gbkData) # 1. 再將 GBK 編碼格式字符串 轉化成 Unicode unicodeStr = gbkData.decode("gbk") print(unicodeStr) # 2. 再將 Unicode 編碼格式字符串轉換成 UTF-8 utf8Str = unicodeStr.encode("UTF-8") print(utf8Str)
原文:https://blog.csdn.net/Ka_Ka314/article/details/81014589
Json與jsonpath再認識與初識