阅读本文需要3分钟
1
这次我们将为大家介绍如何使用 Python 语言来编码和解码 JSON 对象。
1
使用 JSON 函数需要导入 json 库:import json。
函数 | 描述 |
---|---|
json.dumps | 将 Python 对象编码成 JSON 字符串 |
json.loads | 将已编码的 JSON 字符串解码为 Python 对象 |
1
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 格式数据:
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}]
使用参数让 JSON 数据格式化输出:
>>> import json
>>> print (json.dumps({'a': 'Runoob', 'b': 7}, sort_keys=
True,indent=4, separators=(',', ': ')))
{
"a": "Runoob",
"b": 7
}
1
python原始类型向json类型的转化对表:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str, unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
1
json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
以下实例展示了Python 如何解码 JSON 对象:
import json
jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
text = json.loads(jsonData)
print (text)
以上代码执行结果为:
{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}
1
json类型转换到python的类型对照表:
JSON | Python |
---|---|
object | dict |
array | list |
string | unicode |
number (int) | int, long |
number (real) | float |
true | True |
false | False |
null | None |
1
Demjson 是 python 的第三方模块库,可用于编码和解码 JSON 数据,包含了 JSONLint 的格式化及校验功能。
Github 地址:https://github.com/dmeranda/demjson
官方地址:http://deron.meranda.us/python/demjson/
函数 | 描述 |
---|---|
encode | 将 Python 对象编码成 JSON 字符串 |
decode | 将已编码的 JSON 字符串解码为 Python 对象 |
Python encode() 函数用于将 Python 对象编码成 JSON 字符串。
demjson.encode(self, obj, nest_level=0)
以下实例将数组编码为 JSON 格式数据:
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}]
Python 可以使用 demjson.decode() 函数解码 JSON 数据。该函数返回 Python 字段的数据类型。
demjson.decode(self, txt)
以下实例展示了Python 如何解码 JSON 对象:
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}
1
END
发现更多精彩
关注公众号