JSON和JSONPATH

扫码查看

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它使得人们很容易的进行阅读和编写。同时也方便了机器进行解析和生成。适用于进行数据交互的场景,比如网站前台与后台之间的数据交互。

JSON和XML相比较可谓不相上下。

Python 3.X中自带了JSON模块,直接import json就可以使用了。

官方文档:http://docs.python.org/library/json.html

Json在线解析网站:http://www.json.cn/

一下内容参考自:https://www.jb51.net/article/182006.htm

JSON

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

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

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

json模块

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

1.json.dumps()

实现Python类型转化为Json字符串,返回一个str对象,从Python到Json的类型转换对照如

PythonJson
dictobject
list, tuplearray
str, utf-8string
int, floatnumber
Truetrue
Falsefalse
Nonenull 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/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() 序列化时默认使用的ascii编码
# 添加参数 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内置类型序列化为Json对象后写入文件

1
2
3
4
5
6
7
8
9
#!/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格式字符串解码转换成Python对象,从Json到Python的类型转换对照如下:

JsonPython
objectdict
arraylist
stringutf-8
number(int)int
number(real)float
trueTrue
falseFalse
nullNone
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/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数据自动按utf-8存储
print(json.loads(strDict))
# {'city': '北京', 'name': '蚂蚁'}

4.json.load()

读取文件中Json形式的字符串,转换成Python类型

1
2
3
4
5
6
7
8
9
10
11
#!/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文档中抽取指定信息的工具,提供多种语言实现版本,包括:JavaScript、Python、PHP和Java。

JsonPath对于JSON来说,相当于XPATH对于XML。

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

安装方法:下载后解压之后执行 python setup.py install

官方文档:http://goessner.net/articles/JsonPath

JsonPath与XPath语法对比:

JsonPath结构清晰,可读性高,复杂度低,非常容易匹配,下表中对应了XPath的用法。

XpathJSONPath描述
/$根节点
.@现行节点
/. or []取子节点
..n/a取父节点,Jsonpath未支持
//..不管位置,选择所有符合条件的节点
**匹配所有元素节点
@n/a根据属性访问,JsonPath不支持
[][]迭代器(可以在里边做简单的迭代操作,如数组下标,根据内容选值等)
|[,]支持迭代器中做多选
[]?()支持过滤操作
n/a()支持表达式计算
()n/a分组,JsonPath不支持

示例:

以拉勾网城市JSON文件:http://www.lagou.com/lbs/getAllCitySearchLabels.json 为例,获取所有的城市名称。

from urllib import request
import json
import jsonpath

url = "http://www.lagou.com/lbs/getAllCitySearchLabels.json"
headers = {
        "User-Agent": 'Mozilla/5.0 (compatible; U; ABrowse 0.6; Syllable) AppleWebKit/420+ (KHTML, like Gecko)'

    }

req = request.Request(url=url,headers=headers)
response = request.urlopen(req)
html = response.read().decode("utf-8")

#json字符串格式转化为python格式
obj = json.loads(html)
#通过jsonpath提取出name属性的值
city_list = jsonpath.jsonpath(obj,"$..name")
#再将其转化为json格式并写入文件city.json
#ensure_ascii是指是否需要转码为ascii,选择false会转为unicode,方便后面转吗为utf-8
json.dump(city_list,open("city.json","w",encoding='utf-8'),ensure_ascii=False)
12-14 04:54
查看更多