设为首页 加入收藏

TOP

模块讲解----json模块(跨平台的序列化与反序列化)
2017-12-23 06:07:00 】 浏览:92
Tags:模块 讲解 ----json 跨平台 序列化

一、json的特点

1、只能处理简单的可序列化的对象;(字典,列表,元祖)
2、json支持不同语言之间的数据交互;(python  -  go,python - java
 
二、使用场景
1、玩游戏的时候存档和读取记录。
2、虚拟机挂起、保存或者恢复、读档的时候。
 
 
三、语法:
1、简单的数据类型:
 1 1、在内存中进行转换:
 2 import json
 3 #py基本数据类型转换字符串:
 4 r = json.dumps([11,22,33])
 5 #li = '["alex","eric"]'
 6 li = "['alex','eric']"
 7 re = json.loads(li)   #反序列化的时候,一定要使用双引号""。
 8 print(re,type(re))
 9 
10 
11 2、在文件中转换:(在dumps和loads基础上增加了个写读文件)
12 import json
13 
14 文件格式的序列化:
15 li = [11,22,33]
16 json.dump(li,open('db','w'))
17 
18 
19 文件格式的反序列化:
20 li = json.load(open('db','r'))
21 print(li,type(li))

 

2、复杂的数据类型:

序列化:

 1 #!/usr/bin/env python
 2 # -*- coding:utf8 -*-
 3 # Author:Dong Ye
 4 
 5 import json
 6 
 7 
 8 test = r'test.txt'
 9 
10 info  = {
11     'name' : 'alex',
12     'age' : 32
13 
14 }
15 
16 with open(test,'w',encoding='utf-8') as f:
17     f.write( json.dumps(info) )

 

反序列化:

 1 #!/usr/bin/env python
 2 # -*- coding:utf8 -*-
 3 # Author:Dong Ye
 4 
 5 import  json
 6 
 7 test = r'test.txt'
 8 
 9 with open(test,'r',encoding='utf-8') as f:
10     data = json.loads( f.read() )
11     print(data)
12     print(data['name'])
13     print(data['age'])

 

使用场景

调用其他平台的接口时,一般都会返回一个字符串,eg:“字典,列表,url路径等”。
1 import requests
2 import json
3 
4 response = requests.get("http://http://wthrcdn.etouch.cn/weather_mini?ciyp=北京")
5 response.encoding = 'utf-8'
6 
7 dic = json.loads(requests.text)
8 print(response,type(response))
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇我的第一个python web开发框架(1.. 下一篇Python Thrift 简单示例

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目