JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。它基于 ECMAScript (w3c制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
这篇文字将介绍如何使用 Python 语言来编码和解码 JSON 对象。
JSON 函数
使用 JSON 函数需要导入 json 库:import json。
函数 | 描述 |
---|---|
json.dumps | 将 Python 对象编码成 JSON 字符串 |
json.loads | 将已编码的 JSON 字符串解码为 Python 对象 |
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)
实例
以下实例将数组编码为 JSON 格式数据:
使用参数让 JSON 数据格式化输出:
#coding:utf-8
import json
pythonData= {"max": 10,"numRaters": 2,"average": "0.0","min": 0,"subtitle": "未来","author": "青闰","pubdate": "2005-1-1"}
json = json.dumps(pythonData,ensure_ascii=False,sort_keys=True,skipkeys=False,indent=4)
print json
输出:
{
"author": "青闰",
"average": "0.0",
"max": 10,
"min": 0,
"numRaters": 2,
"pubdate": "2005-1-1",
"subtitle": "未来"
}
python 原始类型向 json 类型的转化对照表:
Python | JSON | |
---|---|---|
dict | object | |
list,tuple | array | |
str, unicode | string | |
int, long, float | number | |
True | true | |
False | false | |
None | null |
json.loads
json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。
语法
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
实例
以下实例展示了Python 如何解码 JSON 对象:
#coding:utf-8
import json
#将以下JSON对象解析为python格式,并进行访问,字符串的JSON对象
jsonData= '''{
"rating": {
"max": 10,
"numRaters": 2,
"average": "0.0",
"min": 0
},
"subtitle": "",
"author": [
"青闰"
],
"pubdate": "2005-1-1"
}'''
text = json.loads(jsonData)
print text
#按字典的形式访问元素
for key in text:
print key,text[key]
输出:
#输出text
{u'rating': {u'max': 10, u'numRaters': 2, u'average': u'0.0', u'min': 0}, u'subtitle': u'', u'pubdate': u'2005-1-1', u'author': [u'\u9752\u95f0']}
#访问text元素的结果
rating {u'max': 10, u'numRaters': 2, u'average': u'0.0', u'min': 0}
subtitle
pubdate 2005-1-1
author [u'\u9752\u95f0']
json 类型转换到 python 的类型对照表:
JSON | Python |
---|---|
object | dict |
array | list |
string | unicode |
number (int) | int, long |
number (real) | float |
true | True |
false | False |
null | None |