python3下JSON和JsonPath

1.1   JSON介紹

json簡單說就是javascript中的對象和數組,因此這兩種結構就是對象和數組兩種結構,經過這兩種結構能夠表示各類複雜的結構。javascript

1. 對象:對象在js中表示爲{ }括起來的內容,數據結構爲 { key:value, key:value, ... }的鍵值對的結構,在面向對象的語言中,key爲對象的屬性,value爲對應的屬性值,因此很容易理解,取值方法爲 對象.key 獲取屬性值,這個屬性值的類型能夠是數字、字符串、數組、對象這幾種。html

2.數組:數組在js中是中括號[ ]括起來的內容,數據結構爲 ["Python", "javascript", "C++", ...],取值方式和全部語言中同樣,使用索引獲取,字段值的類型能夠是 數字、字符串、數組、對象幾種。java

 

1.2   JSON模塊的四個功能

json模塊提供了四個功能:dumps、dump、loads、load,用於字符串 和 python數據類型間進行轉換。python

1. json.loads()json

json.loads()實現把Json格式字符串解碼轉換成Python對象 從json到python的類型轉化對照以下:api

JSON數組

Python數據類型數據結構

Json格式字符串解碼轉換成Python對象app

object工具

dict

array

list

number(int)

int,long

number(real)

float

true

True

false

False

null

None

 

例子:

import json

 

# 數據

js_list = '[1, 2, 3, 4]'

js_dict = '{"name": "聽海", "age": "年年18"}'

 

# 數據轉換前的類型

print(type(js_list))

print(type(js_dict))

 

# json.loads()實現把Json格式字符串解碼轉換成Python對象

List = json.loads(js_list)

Dict = json.loads(js_dict)  # json數據自動按Unicode存儲

 

print('--------------------------')

# 轉換後的顯示

print(List)

print(Dict)

 

#數據轉換後的類型

print(type(List))

print(type(Dict))

 

運行結果:

<class 'str'>

<class 'str'>

--------------------------

[1, 2, 3, 4]

{'age': '年年18', 'name': '聽海'}

<class 'list'>

<class 'dict'>

 

2. json.dumps()

json.dumps()實現把python類型轉化爲json字符串,返回一個str對象 把一個Python對象編碼轉換成Json字符串,從python原始類型向json類型的轉化對照以下:

Python數據類型

JSON

python類型轉化爲json字符串

dict

object

list

array

int、long、float

number

str、Unicode

string

True

true

False

false

None

null

 

例子:

import json

 

listStr = [1, 2, 3, 4]

tupleStr = ("python3", "selenium3", "appium", "java")

dictStr = {"name": "聽海", "age": "年年18"}

 

# 轉換前的格式

print(type(listStr))

print(type(tupleStr))

print(type(dictStr))

 

# 把 python類型轉化爲json字符串,返回一個str對象。

js_strList=json.dumps(listStr)

js_tupleStr = json.dumps(tupleStr)

# json.dumps() 序列化時默認使用的ascii編碼,添加參數 ensure_ascii=False 禁用ascii編碼,按utf-8編碼。

js_dictStr=json.dumps(dictStr,ensure_ascii=False)

 

print("---------------")

# 打印轉換後數據顯示。

print(js_strList)

print(js_tupleStr)

print(js_dictStr)

 

# 轉換後的格式

print(type(js_strList))

print(type(js_tupleStr))

print(type(js_dictStr))

 

運行結果:

<class 'list'>

<class 'tuple'>

<class 'dict'>

---------------

[1, 2, 3, 4]

["python3", "selenium3", "appium", "java"]

{"name": "聽海", "age": "年年18"}

<class 'str'>

<class 'str'>

<class 'str'>

 

注意:json.dumps() 序列化時默認使用的ascii編碼,添加參數 ensure_ascii=False 禁用ascii編碼,按utf-8編碼顯示。

 

3. json.dump()

將Python內置類型序列化爲json對象後寫入文件。

例子:

import json

 

listStr = [{"a1": "1"}, {"b1": "2"}]

json.dump(listStr, open("listStr.json","w"), ensure_ascii=False)

 

dictStr = {"a2": "3", "b2": "4"}

json.dump(dictStr, open("dictStr.json","w"), ensure_ascii=False)

 

運行結果:

 

會在當前目錄生成 listStr.json 文件和 dictStr.json 2個文件。

 

4. json.load()

讀取文件中json形式的字符串元素 轉化成python類型。

例子:

接口文檔中一個請求報文示例,咱們就把這個示例中的json形式的報文轉換成python類型。

 

1.在當前目錄新建一個名爲「接口請求報文.json」文件。

 

代碼實現:

import json

 

js_t_py = json.load(open("./接口請求報文.json",encoding="utf-8"))

print(js_t_py)

print(type(js_t_py))

 

運行結果:

 

1.3   JsonPath

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

JsonPath 對於 JSON 來講,至關於 XPATH 對於 XML。

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

 

 

官方使用說明文檔:http://goessner.net/articles/JsonPath

14.3.1 JsonPath的安裝

安裝方法一:點擊Download URL連接下載jsonpath,解壓以後執行python setup.py install。

安裝方法二:使用 pip install jsonpath 命令直接安裝。

 

14.3.2 JsonPath 官方示例

{ "store": {

    "book": [

      { "category": "reference",

        "author": "Nigel Rees",

        "title": "Sayings of the Century",

        "price": 8.95

      },

      { "category": "fiction",

        "author": "Evelyn Waugh",

        "title": "Sword of Honour",

        "price": 12.99

      },

      { "category": "fiction",

        "author": "Herman Melville",

        "title": "Moby Dick",

        "isbn": "0-553-21311-3",

        "price": 8.99

      },

      { "category": "fiction",

        "author": "J. R. R. Tolkien",

        "title": "The Lord of the Rings",

        "isbn": "0-395-19395-8",

        "price": 22.99

      }

    ],

    "bicycle": {

      "color": "red",

      "price": 19.95

    }

  }

}

14.3.3 JsonPath與XPath語法對比

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

Xpath

JSONPath

描述

/

$

根節點

.

@

現行節點

/

.or[]

取子節點

..

不支持

取父節點,Jsonpath不支持

//

..

忽略位置,選擇全部符合條件的條件

*

*

匹配全部元素節點

@

不支持

根據屬性訪問,Json不支持,由於Json是個Key-value遞歸結構,不須要。

[]

[]

迭代器標示(能夠在裏邊作簡單的迭代操做,如數組下標,根據內容選值等)

|

[,]

支持迭代器中作多選。

[]

?()

支持過濾操做。

不支持

()

支持表達式計算

()

不支持

分組,JsonPath不支持

示例語法對比。

Xpath

JSONPath

示例結果

/store/book/author

$.store.book[*].author

the authors of all books in the store
以下:
"Nigel Rees"
"Evelyn Waugh"
"Herman Melville"
"J. R. R. Tolkien"

//author

$..author

all authors

/store/*

$.store.*

all things in store, which are some books and a red bicycle.

/store//price

$.store..price

the price of everything in the store.

//book[3]

$..book[2]

the third book

//book[last()]

$..book[(@.length-1)]
$..book[-1:]

the last book in order.

//book[position()<3]

$..book[0,1]
$..book[:2]

the first two books

//book[isbn]

$..book[?(@.isbn)]

filter all books with isbn number

//book[price<10]

$..book[?(@.price<10)]

filter all books cheapier than 10

//*

$..*

all Elements in XML document. All members of JSON structure.

 

1.4   案例

案例:

以拉勾網城市JSON文件 http://www.lagou.com/lbs/getAllCitySearchLabels.json 爲例,獲取全部城市。

代碼實現:

import jsonpath

 

url = 'http://www.lagou.com/lbs/getAllCitySearchLabels.json'

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}

r = requests.get(url,headers=headers)

html = r.text

 

# 把json格式字符串轉換成python對象

jsonobj = json.loads(html)

 

# 從根節點開始,匹配name節點

citylist = jsonpath.jsonpath(jsonobj,'$..name')

 

print(citylist)

print(type(citylist))

#新建一個city.json文件,並設置編碼格式爲utf-8

fp = open('city.json','w',encoding="utf-8")

 

content = json.dumps(citylist, ensure_ascii=False)

print(content)

 

fp.write(content)

fp.close()

 

運行結果:

 

注意事項:

json.loads() 是把 Json格式字符串解碼轉換成Python對象,若是在json.loads的時候出錯,要注意被解碼的Json字符的編碼。

若是傳入的字符串的編碼不是UTF-8的話,須要指定字符編碼的參數 encoding

dataDict = json.loads(jsonStrGBK);

dataJsonStr是JSON字符串,假設其編碼自己是非UTF-8的話而是GBK 的,那麼上述代碼會致使出錯,改成對應的:

dataDict = json.loads(jsonStrGBK, encoding="GBK");

若是 dataJsonStr經過encoding指定了合適的編碼,可是其中又包含了其餘編碼的字符,則須要先去將dataJsonStr轉換爲Unicode,而後再指定編碼格式調用json.loads()

dataJsonStrUni = dataJsonStr.decode("GB2312");

dataDict = json.loads(dataJsonStrUni, encoding="GB2312");

相關文章
相關標籤/搜索