您现在的位置是:首页 > web开发 > Json与JsonPath

Json与JsonPath

web开发作者:dayu日期:11天前点击:3

# -*- conding:utf-8 -*-
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对象后写入文件

# -*- conding:utf-8 -*-
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的类型转换对照如下:
技术分享

# -*- conding:utf-8 -*-
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类型

# -*- conding:utf-8 -*-
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的用法。

技术分享

示例:

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

# -*- conding:utf-8 -*-
import urllib.request
import json
import jsonpath

# 拉勾网城市JSON文件
url = ‘http://www.lagou.com/lbs/getAllCitySearchLabels.json‘
# User-Agent头
header = {‘User-Agent‘:‘Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36‘}

# url 连同 headers,一起构造Request请求,这个请求将附带 chrome 浏览器的User-Agent
request = urllib.request.Request(url, headers = header)

# 向服务器发送这个请求
response = urllib.request.urlopen(request)

# 获取页面内容:bytes
html = response.read()

# 转码:bytes转str
html = html.decode("utf-8")

# 把json格式字符串转换成python对象
obj = json.loads(html)

# 从根节点开始,匹配name节点
city_list = jsonpath.jsonpath(obj, ‘$..name‘)

# 打印获取的name节点
print(city_list)
# 打印其类型
print(type(city_list))

# 写入本地磁盘文件
with open("city.json", "w", encoding = "utf-8") as f:
content = json.dumps(city_list, ensure_ascii = False)
f.write(content)

Json与JsonPath

原文地址:http://www.cnblogs.com/niansi/p/7225844.html


下一篇       上一篇