python3下JSON和JsonPath

1.1   JSON介绍

json简单说就是javascript中的对象和数组,所以这两种结构就是对象和数组两种结构,通过这两种结构可以表示各种复杂的结构。

1. 对象:对象在js中表示为{ }括起来的内容,数据结构为 { key:value, key:value, ... }的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为 对象.key 获取属性值,这个属性值的类型可以是数字、字符串、数组、对象这几种。

2.数组:数组在js中是中括号[ ]括起来的内容,数据结构为 ["Python", "javascript", "C++", ...],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是 数字、字符串、数组、对象几种。

 

1.2   JSON模块的四个功能

json模块提供了四个功能:dumps、dump、loads、load,用于字符串 和 python数据类型间进行转换。

1. json.loads()

json.loads()实现把Json格式字符串解码转换成Python对象 从json到python的类型转化对照如下:

JSON

Python数据类型

Json格式字符串解码转换成Python对象

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");

猜你喜欢

转载自www.cnblogs.com/tinghai8/p/9217629.html