×
Python 基础教程Python 简介Python 环境搭建Python 中文编码Python 基础语法Python 变量类型Python 运算符Python 条件语句Python 循环语句Python While循环语句Python for 循环语句Python 循环嵌套Python break 语句Python continue 语句Python pass 语句Python 数字Python 字符串Python 列表(Lists)Python 元组Python 字典(Dictionary)Python 日期和时间Python 函数Python 模块Python 文件I/OPython File(文件) 方法Python 异常处理Python OS 文件/目录方法Python 内置函数

Python 高级教程

Python 面向对象Python 正则表达式Python CGI编程python MysqlPython SMTPPython 多线程Python XML解析python GUI编程(Tkinter)Python 2.x与3​​.x版本区别Python IDEPython JSONPython 100例

Python JSON


本章节我们将为大家介绍如何使用 Python 语言来编码和解码 JSON 对象。


环境配置

在使用 Python 编码或解码 JSON 数据前,我们需要先安装 JSON 模块。本教程我们会下载 Demjson 并安装:


$tar xvfz demjson-1.6.tar.gz
$cd demjson-1.6
$python setup.py install

JSON 函数

函数描述
encode 将 Python 对象编码成 JSON 字符串
decode将已编码的 JSON 字符串解码为 Python 对象

encode

Python encode() 函数用于将 Python 对象编码成 JSON 字符串。

语法


demjson.encode(self, obj, nest_level=0)

实例

以下实例将数组编码为 JSON 格式数据:


#!/usr/bin/python
import demjson

data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]

json = demjson.encode(data)
print json

以上代码执行结果为:


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

decode

Python 可以使用 demjson.decode() 函数解码 JSON 数据。该函数返回 Python 字段的数据类型。

语法


demjson.decode(self, txt)

实例

以下实例展示了Python 如何解码 JSON 对象:


#!/usr/bin/python
import demjson

json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

text = demjson.decode(json)
print  text

以上代码执行结果为:


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

分类导航

关注微信下载离线手册

bootwiki移动版 bootwiki
(群号:472910771)