可以用函數 json.dumps()
將 Python 對象編碼轉換為字符串形式。
例如:
1
2
3
4
|
import json python_obj = [[ 1 , 2 , 3 ], 3.14 , 'abc' ,{ 'key1' :( 1 , 2 , 3 ), 'key2' :[ 4 , 5 , 6 ]}, True , False , None ] json_str = json.dumps(python_obj) print (json_str) |
輸出:
[[1, 2, 3], 3.14, "abc", {"key1": [1, 2, 3], "key2":
[4, 5, 6]}, true, false, null]
簡單類型對象編碼后的字符串和其原始的 repr()結果基本是一致的,但有些數據類型,如上例中的元組(1, 2, 3)被轉換成了[1, 2, 3](json 模塊的 array 數組形式)。
可以向函數 json.dumps()傳遞一些參數以控制轉換的結果。例如,參數 sort_keys=True 時,dict 類型的數據將按key(鍵)有序轉換:
1
2
3
4
5
|
data = [{ 'xyz' : 3.0 , 'abc' : 'get' , 'hi' : ( 1 , 2 ) }, 'world' , 'hello' ] json_str = json.dumps(data) print (json_str) json_str = json.dumps(data, sort_keys = True ) print (json_str) |
輸出:
[{"xyz": 3.0, "abc": "get", "hi": [1, 2]}, "world", "hello"]
[{"abc": "get", "hi": [1, 2], "xyz": 3.0}, "world", "hello"]
即當 sort_keys=True 時,轉換后的 json 串對于字典的元素是按鍵(key)有序的。
對于結構化數據,可以給參數 indent 設置一個值(如 indent=3)來產生具有縮進的、閱讀性好的json 串:
1
2
|
json_str = json.dumps(data, sort_keys = True ,indent = 3 ) print (json_str) |
輸出:
[
{
"abc": "get",
"hi": [
1,
2
],
"xyz": 3.0
},
"world",
"hello"
]
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注服務器之家的更多內容!
原文鏈接:https://blog.csdn.net/m0_64430632/article/details/121598998