一、将对象转为json字符串
-
json.dumps
:将 Python 对象编码成 JSON 字符串 -
json.loads
:将已编码的 JSON 字符串解码为 Python 对象
1
2
3
4
5
6
7
8
9
|
import json data = [ { 'name' : 'autofelix' , 'age' : 27 }, { 'name' : '飞兔' , 'age' : 26 } ] result = json.dumps(data, ensure_ascii = False ) print (result) |
二、格式化输出
1
2
3
4
5
6
7
8
9
10
|
import json data = [ { 'name' : 'autofelix' , 'age' : 27 }, { 'name' : '飞兔' , 'age' : 26 } ] # 格式化输出 result = json.dumps(data, sort_keys = True , indent = 4 , separators = ( ',' , ': ' )) print (result) |
三、将json字符串转为对象
1
2
3
4
5
6
|
import json data = "[{ 'name' : 'autofelix', 'age' : 27}, { 'name' : '飞兔', 'age' : 26}]" result = json.loads(data) print (result) |
四、安装demjson
- 是 python 的第三方模块库,可用于编码和解码 JSON 数据
- 包含了 JSONLint 的格式化及校验功能
1
|
pip install demjson |
五、将对象转为json字符串
-
encode
:将 Python 对象编码成 JSON 字符串 -
decode
:将已编码的 JSON 字符串解码为 Python 对象
1
2
3
4
5
6
7
8
9
|
import demjson data = [ { 'name' : 'autofelix' , 'age' : 27 }, { 'name' : '飞兔' , 'age' : 26 } ] result = demjson.encode(data) print (result) |
六、将json字符串转为对象
1
2
3
4
5
6
|
import demjson data = "[{ 'name' : 'autofelix', 'age' : 27}, { 'name' : '飞兔', 'age' : 26}]" result = demjson.decode(data) print (result) |
到此这篇关于python 包中的JSON 轻量数据操作教程的文章就介绍到这了,更多相关JSON 轻量数据操作内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.51cto.com/autofelix/5212309