V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
zyhyab4691
V2EX  ›  2019

JSON 与 JSONPath

  •  
  •   zyhyab4691 · 2019-03-20 11:10:14 +08:00 · 1261 次点击
    这是一个创建于 1858 天前的主题,其中的信息可能已经有所发展或是发生改变。

    JSON ( JavaScript Object Notation )是一种轻量级的数据交换格式,因为它良好的可读性与易于机器进行解析和生成等特性,在当前的数据整理和收集中得到了广泛的应用。

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

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

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

    Json 在线解析网站: http://www.rjson.com

    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 的类型转换对照如下:

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

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2910 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 07:36 · PVG 15:36 · LAX 00:36 · JFK 03:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.