十一、数据提取之Json与JsonPath

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

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

1、JSON

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

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

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

2、import json

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

  2.1 json.loads()

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

    

import json

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

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

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

json.loads(strDict) # json数据自动按Unicode存储
# {u'city': u'u5317u4eac', u'name': u'u5927u732b'}

  2.2 json.dumps()

    json.dumps()实现python类型转化为json字符串,返回一个str对象。

    从python原始类型向json类型的转化对照如下:

    

import json
import chardet

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

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

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

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

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

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

chardet.detect(json.dumps(dictStr, ensure_ascii=False))
# {'confidence': 0.99, 'encoding': 'utf-8'}

  2.3 Json.dump()

    将python内置类型序列化为json对象后写入文件

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)

  2.4 json.load()

    读取文件中json形式的字符串元素,转换成python类型

import json

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

# [{u'city': u'u5317u4eac'}, {u'name': u'u5927u5218'}]

strDict = json.load(open("dictStr.json"))
print strDict
# {u'city': u'u5317u4eac', u'name': u'u5927u5218'}

3、JsonPath

  JsonPath 是一种信息抽取类库,是从JSON文档中抽取指定信息的工具,提供多种语言实现版本,包括:Javascript, Python, PHP 和 Java。

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

  安装:`pip install jsonpath`

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

  3.1 jsonpath与xpath语法对比

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

  3.2 示例

# jsonpath_lagou.py

import requests
import jsonpath
import json
import chardet

url = 'http://www.lagou.com/lbs/getAllCitySearchLabels.json'
response = equests.get(url)
html = response.text

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

# 从根节点开始,匹配name节点
citylist = jsonpath.jsonpath(jsonobj,'$..name')

print citylist
print type(citylist)
fp = open('city.json','w')

content = json.dumps(citylist, ensure_ascii=False)
print content

fp.write(content.encode('utf-8'))
fp.close()

  

  

原文地址:https://www.cnblogs.com/nuochengze/p/12860226.html