Python数据提取之JSON与JsonPATH

发布 : 2017-06-02 分类 : Python 浏览 :
1
2
3
4
5
6
7
8
9
10
11
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,它使得人们很容易的进行阅读和编写

同时也方便了机器进行解析和生成。适用于进行数据交互的场景,比如网站前台与后台之间的数据交互

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

Python 2.7中自带了JSON模块,直接import json就可以使用了

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

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

JOSN

json简单说就是javascript中的对象数组

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

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

import json

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

json.loads()

1
把Json格式字符串解码转换成Python对象 从json到python的类型转化对照如下:
JSON Python
object dict
array list
string unicode
number(int) int,long
number(real) float
true True
false False
null None
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# -*- coding: utf-8 -*-

# json_loads.py

import json

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

strDict = '{"city": "北京", "name": "大猫"}'

print(json.loads(strList))
# [1, 2, 3, 4]

print(json.loads(strDict)) # json数据自动按Unicode存储
# {u'city': u'\u5317\u4eac', u'name': u'\u5927\u732b'}

Markdown

json.dumps()

1
2
3
实现python类型转化为json字符串,返回一个str对象 把一个Python对象编码转换成Json字符串

从python原始类型向json类型的转化对照如下:
Python JSON
dict object
list,tuple array
str,unicode string
int,long,float number
True true
False false
None null
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
30
31
# -*- coding: utf-8 -*-

# json_dumps.py

import json
import chardet

listStr = [1, 2, 3, 4]
tupleStr = (1, 2, 3, 4)
dictStr = {"city": "北京", "name": "大猫"}

print(json.dumps(listStr))
# '[1, 2, 3, 4]'
print(json.dumps(tupleStr))
# '[1, 2, 3, 4]'

# 注意:json.dumps() 序列化时默认使用的ascii编码
# 添加参数 ensure_ascii=False 禁用ascii编码,按utf-8编码
# chardet.detect()返回字典, 其中confidence是检测精确度

# print(json.dumps(dictStr))
# '{"city": "\\u5317\\u4eac", "name": "\\u5927\\u5218"}'

# print(chardet.detect(json.dumps(dictStr)))
# {'confidence': 1.0, 'encoding': 'ascii'}

print(json.dumps(dictStr, ensure_ascii=False))
# {"city": "北京", "name": "大刘"}

# print(chardet.detect(json.dumps(dictStr, ensure_ascii=False)))
# {'confidence': 0.99, 'encoding': 'utf-8'}
1
chardet是一个非常优秀的编码识别模块,可通过pip安装

json.dump()

1
将Python内置类型序列化为json对象后写入文件
1
2
3
4
5
6
7
8
# -*- coding: utf-8 -*-
import json

listStr = [{"city": "北京"}, {"name": "大刘"}]
json.dump(listStr, open("listStr.json", "w"), ensure_ascii=False)

dictStr = {"city": "北京", "name": "大刘"}
json.dump(dictStr, open("dictStr.json", "w"), ensure_ascii=False)

json.load()

1
读取文件中json形式的字符串元素 转化成python类型
1
2
3
4
5
6
7
8
# -*- coding: utf-8 -*-
import json

strList = json.load(open("listStr.json"))
print(strList)

strDict = json.load(open("dictStr.json"))
print(strDict)

Markdown

JsonPath

1
2
3
4
5
6
7
8
9
JsonPath 是一种信息抽取类库,是从JSON文档中抽取指定信息的工具,提供多种语言实现版本,包括:Javascript,Python,PHP和Java

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

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

安装方法:点击Download URL链接下载jsonpath,解压之后执行python setup.py install

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

JsonPath与XPath语法对比

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

Markdown

根据拉勾网JOSN文件,获取所有城市

1
拉勾网城市JSON文件http://www.lagou.com/lbs/getAllCitySearchLabels.json为例,获取所有城市
本文作者 : Matrix
原文链接 : https://matrixsparse.github.io/2017/06/02/Python数据提取之JSON与JsonPATH/
版权声明 : 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!

知识 & 情怀 | 二者兼得

微信扫一扫, 向我投食

微信扫一扫, 向我投食

支付宝扫一扫, 向我投食

支付宝扫一扫, 向我投食

留下足迹