本文實例講述了Python3實現的字典、列表和json對象互轉功能。分享給大家供大家參考,具體如下:
python3可以使用json模塊操作json
json.dumps()
: 對json進行編碼,對應php的json_encode()
json.loads()
: 對json進行解碼,對應php的json_decode()
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
#!/usr/bin/python3 import json #python字典類型轉換為json對象 data = { 'id' : 1 , 'name' : 'test1' , 'age' : '1' } data2 = [{ 'id' : 1 , 'name' : 'test1' , 'age' : '1' },{ 'id' : 2 , 'name' : 'test2' , 'age' : '2' }] json_str = json.dumps(data) print ( "python原始數據:" , repr (data)) print ( "json對象:" , json_str) json_str2 = json.dumps(data2) print ( "python原始數據:" , repr (data2)) print ( "json對象:" , json_str2) # 將json對象轉換為python字典 data3 = json.loads(json_str) print ( "data3['name']: " , data3[ 'name' ]) print ( "data3['age']: " , data3[ 'age' ]) |
執行結果
[root@mail pythonCode]# python3 test.py
python原始數據: {'id': 1, 'name': 'test1', 'age': '1'}
json對象: {"id": 1, "name": "test1", "age": "1"}
python原始數據: [{'id': 1, 'name': 'test1', 'age': '1'}, {'id': 2, 'name': 'test2', 'age': '2'}]
json對象: [{"id": 1, "name": "test1", "age": "1"}, {"id": 2, "name": "test2", "age": "2"}]
data3['name']: test1
data3['age']: 1
希望本文所述對大家Python程序設計有所幫助。
原文鏈接:https://blog.csdn.net/nuli888/article/details/51960725