函数和常用模块【day06】:json模块(十一)

本节内容

1、dumps序列化和loads反序列化

2、dump序列化和load反序列化

3、序列函数

1、dumps序列化和loads反序列化

dumps()序列化

1
2
3
4
5
6
7
8
9
10
11
12
13
import   json    #导入json模块
 
info  =  {
     'name' : "zhangqigao" ,
     "age" : 22
}
 
with  open ( "test.txt" , "w" ) as f:   #以普通模式写入
     data  =  json.dumps(info)  #把内存对象转为字符串
     f.write(data)    #写到文件中
 
#text.txt文件中的内容
{ "name" "zhangqigao" "age" 22 }

loads()反序列化

1
2
3
4
5
6
7
8
9
import  json
 
with  open ( "test.txt" , "r" ) as f:   #以普通模式读
     data  =  json.loads(f.read())    #用loads反序列化
 
print (data.get( "age" ))
 
#输出
22

2、dump序列化和load反序列化

dump()序列化

1
2
3
4
5
6
7
8
9
10
11
12
import   json
 
info  =  {
     'name' : "zhangqigao" ,
     "age" : 22
}
 
with  open ( "test.txt" , "w" ) as f:    #文件以写的方式打开
     json.dump(info,f)     #第1个参数是内存的数据对象 ,第2个参数是文件句柄
 
#text.txt文件中的内容
{ "name" "zhangqigao" "age" 22 }

 load()反序列化

1
2
3
4
5
6
7
8
9
import  json
 
with  open ( "test.txt" , "r" ) as f:    #以读的方式打开文件
     data  =  json.load(f)   #输入文件对象
 
print (data.get( "age" ))
 
#输出
22

3、序列化函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import   json
 
def  sayhi(name):   #函数
     print ( "name:" ,name)
 
info  =  {
     'name' : "zhangqigao" ,
     "age" : 22 ,
     "func" :sayhi     #引用sayhi函数名
}
 
with  open ( "test.txt" , "w" ) as f:
     json.dump(info,f)    #序列化info数据对象
 
#输出
  File  "D:\Python\Python35\lib\json\encoder.py" , line  403 in  _iterencode_dict
     yield  from  chunks
   File  "D:\Python\Python35\lib\json\encoder.py" , line  436 in  _iterencode
     =  _default(o)
   File  "D:\Python\Python35\lib\json\encoder.py" , line  179 in  default
     raise  TypeError( repr (o)  +  " is not JSON serializable" )
TypeError: <function sayhi at  0x00000000006DD510 is  not  JSON serializable   #不支持jsom序列化

小结:

  1. dumps和loads是成对使用的,dump和load是成对使用的。
  2. dumps和loads由于序列化的是内容,所以后面要加s,但是dump和load序列化的内容是对象,所以单数。
  3. json只能处理简单的数据类型,例如:字典、列表、字符串等,不能处理函数等复杂的数据类型。
  4. json是所有语言通用的,所有语言都支持json,如果我们需要python跟其他语言进行数据交互,那么就用json格式。

转载于:https://www.cnblogs.com/luoahong/p/7196089.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值