Python-json模块的使用

数据的分类:
非结构化的数据: html等
处理方式:正则表达式,xpath
结构化数据: json,xml
处理方法:转换为Python数据类型

一,json数据

JSon是一种轻量级的数据交换结构,他使得人们很容易进行阅读和编写,同时方便了机器进行解析和生成。适用于进行数据交换场景,比如网站前台与后台之间的数据交互。

json数据存在手机版的网页,因此查找时需要将网页改为手机版

二,Python数据和json数据之间的转换

1. json.loads()
把Json格式字符串解码转换成Python对象 从json到python的类型转化对照如下:
Python-json模块的使用

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'\u5317\u4eac', u'name': u'\u5927\u732b'}

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

从python原始类型向json类型的转化对照如下:
Python-json模块的使用

# json_dumps.py

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'}

3.爬取豆瓣网的热门视频:
https://movie.douban.com/
切换到手机模式,寻找类型为json的数据类型,在response中查找有没有想要的电影标题
Python-json模块的使用
找到后我们找到请求网址
Python-json模块的使用

通过get方法访问:

#encoding:utf-8
import requests
import json
from pprint import pprint
url = "https://movie.douban.com/j/search_subjects?type=movie&tag=%E7%83%AD%E9%97%A8&page_limit=100&page_start=1"
response = requests.get(url)

ret1 = response.json()  #转换方法1
ret2 = json.loads(response.content)
pprint(ret2) #通过pprint()格式化输出

Python-json模块的使用