JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。

1、JSON 函数

使用 JSON 函数需要导入 json 库:import json

函数 描述
json.dumps 将 Python 对象编码成 JSON 字符串
json.loads 将已编码的 JSON 字符串解码为 Python 对象

(1)json.dumps

json.dumps 用于将 Python 对象编码成 JSON 字符串。

语法

json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)

举例:

#!/usr/bin/python
import json data = { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 }
json = json.dumps(data)
print json

执行结果:

{"a": 1, "c": 3, "b": 2, "e": 5, "d": 4}

python 原始类型向 json 类型的转化对照表:

Python JSON
dict object
list, tuple array
str, unicode string
int, long, float number
True true
False false
None null

(2)json.loads

json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。

语法

json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

举例:

#coding: utf-8
import json json_str = """
{
"id" : 1,
"name" : "python"
}
"""
res = json.loads(json_str) print res
print(res['id']) #
print(res['name']) # python

执行结果:

{u'id': 1, u'name': u'python'}
1
python

json 类型转换到 python 的类型对照表:

JSON Python
object dict
array list
string unicode
number (int) int, long
number (real) float
true True
false False
null None

最新文章

  1. iOS开发系列--C语言之存储方式和作用域
  2. C#中事件的使用
  3. Python快速建站系列-Part.Five.1-个人主页及发表文章
  4. 项目启动异常java.lang.OutOfMemoryError: PermGen space
  5. (转)c#多线程 Invoke方法的使用
  6. android 小知识点
  7. Nagios新添加的hosts和services有时显示,有时不显示问题解决
  8. PowerDesigner15在生成SQL时报错Generation aborted due to errors detected during the verification of the mod
  9. BZOJ 1005: [HNOI2008]明明的烦恼( 组合数学 + 高精度 )
  10. PHP扩展memcache模
  11. Android 四大组件学习之ContentProvider四
  12. Netfilter的使用和实现
  13. Python开发【前端篇】CSS
  14. new words
  15. C# Lambda 表达式学习之(四):动态构建类似于 c => c.Age == 2 || c.Age == 5 || c => c.Age == 17 等等一个或多个 OrElse 的表达式
  16. 从零开始搭建FAQ引擎--深度语义匹配
  17. 给 vue项目添加ESLint
  18. Thinkphp时间转换与统计的问题
  19. Java技术体系总结
  20. 根据URL获取参数值得出json结果集,对外给一个接口让别人调用

热门文章

  1. 多态、抽象类、接口_DAY09
  2. Android返回系统Home桌面
  3. 全网最详细的Windows系统里PLSQL Developer 64bit安装之后的一些配置(图文详解)
  4. 【教程向】——基于hexo+github搭建私人博客
  5. Linux信号和trap命令的使用
  6. spring-boot-mail
  7. 对Java虚拟机理解
  8. new image的使用
  9. 我的菜单在母版页,如何更改菜单点击后的效果 Ver2
  10. ASP.NET开发,且编且改,分清职责