学习笔记(10):150讲轻松搞定Python网络爬虫-JSON字符串转换成Python对象

立即学习:https://edu.csdn.net/course/play/24756/280717?utm_source=blogtoedu

  1. dump是从文件里面dump,dumps是从str里面dump,dumps 是dumps string的简写
  2. load是从文件里面load,loads是从str里面load,loads 是load string的简写
  3. 注意load的文件编码格式应当与json文件的编码格式一致
# !/usr/bin/python
# Filename: json的loads和load.py
# Data    : 2020/06/23
# Author  : --king--
# ctrl+alt+L自动加空格格式化


import json

# loads:json字符串读取为Python列表
json_str = '[{"name": "三国演义", "price": 18.8}, {"name": "水浒传", "price": 19.9}]'
print(type(json_str))
books = json.loads(json_str,encoding='utf-8')
print(type(books))
print(books)

# load:将jsdon文件以只读模式读取为python格式
with open('a.json','r',encoding='utf-8') as fp:
    result = json.load(fp)
    print(result)
    print(type(result))

 

你可能感兴趣的:(150天学会Python爬虫)