飞道的博客

Python爬虫基础讲解(十):数据持久化——json

351人阅读  评论(0)

目的:将Python对象编码为JSON字符串,并将JSON字符串解码为Python对象。

json模块提供了API,将内存中的Python对象转换为」JSON序列。JSON具有以多种语言(尤其是JavaScript)实现的优点。它在RESTAPI中 Web服务端和客户端之间的通信被广泛应用,同时对于应用程序间通信需求也很有用。下面演示如何将一个Python数据结构转换为JSON:

 

关注微信公众号,每天都有免费的Python项目案例教学讲解

1. 编码和解码

Python 的默认原生类型(str, int,float,list,tuple和dict)。


  
  1. import json
  2. data = {
  3. 'name ' : 'ACME',
  4. ' shares ' : 100,
  5. 'price ' : 542.23
  6. }
  7. json_str = json.dumps( data)
  8. print(json_str)

表面上看,类似于Python repr()的输出。虽然内容看似是一样,但是类型却已经发生改变

print(type(json_str))

从无序的字典到有序的字符串,这个过程被称之为序列化。
最终我们将json保存到文件


  
  1. with open( 'data.json ', mode= 'w', encoding= 'utf-8') as f:
  2. f.write(json_str)

1.1 中文字符串问题


  
  1. import json
  2. data = {
  3. 'name ' : '青灯',
  4. 'shares': 100,
  5. 'price' : 542.23
  6. }
  7. #将字典序列化为json
  8. json_str = json.dumps( data)
  9. # 写入json数据
  10. with open( ' data.json',mode= 'w', encoding= 'utf-8 ' ) as f:
  11. f.write(json_str)

  
  1. # filename:data.json
  2. { "name": "\u9752\u706f""shares" : 100"price": 542.23}

解决办法: json_str = json. dumps(data,ensure_ascii=False)

2. 读取数字

将json数据变为字典类型的这个过程被称之为反序列化


  
  1. #读取json数据
  2. with open( ' data.json ', 'r', encoding= 'utf-8') as f:
  3. #反序列化
  4. data = json .1oad(f)
  5. #打印数据
  6. print( data)
  7. print( data[ 'name '])

3. 格式化输出

JSON的结果是更易于阅读的。dumps()函数接受几个参数以使输出更易读结果。


  
  1. import json
  2. data = { 'a ' : 'A''b' : ( 24), 'c' : 3.0}
  3. print( 'DATA: ', repr( data)) # DATA: { 'a' : 'A''b ': ( 24), 'c': 3.0}
  4. unsorted = json.dumps( data)
  5. print( '7SON: ', json.dumps( data)) #JSON: { "a": "A""b":[ 24], "c": 3.03}

编码,然后重新解码可能不会给出完全相同类型的对象。

特别是,元组成为了列表。

JSON跟Python中的字典其实是一样一样的,事实上JSON的数据类型和Python的数据类型是很容易找到对应关系的,如下面两张表所示。

 


转载:https://blog.csdn.net/m0_48405781/article/details/117225955
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场