• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
火磷
Memory will fade,but not notes.
博客园    首页    新随笔    联系   管理    订阅  订阅
python中json的使用

在编写接口传递数据时,往往需要使用JSON对数据进行封装。python和json数据类型的转换,看作为编码与解码。

编码:json.dumps()

PythonJSON
dict object
list, tuple array
str string
int, float, int- & float-derived Enums number
True true
False false
None null

解码:json.loads()

JSONPython
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

普通的字典类型:

1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 
4 import json
5 
6 d = dict(name='Bob', age=20, score=88)
7 print '编码前:'
8 print type(d)
9 print d

编码后的JSON类型:

1 # python编码为json类型,json.dumps()
2 en_json = json.dumps(d)
3 print '编码后:'
4 print type(en_json)
5 print en_json

 

解码后的Python类型:

1 # json解码为python类型,json.loads()
2 de_json = json.loads(en_json)
3 print '解码后:'
4 print type(de_json)
5 print de_json

解析后Python类型:

1 # eval()解析json
2 d = dict(name='Bob', age=20, score=88)
3 en_json = json.dumps(d)
4 de_json = eval(en_json)
5 print '解析后:'
6 print type(de_json)
7 print de_json

!!!

 

posted on 2017-12-06 15:41  火磷  阅读(35858)  评论(2)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3