可以用函數(shù) json.dumps()
將 Python 對象編碼轉(zhuǎn)換為字符串形式。
例如:
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()結(jié)果基本是一致的,但有些數(shù)據(jù)類型,如上例中的元組(1, 2, 3)被轉(zhuǎn)換成了[1, 2, 3](json 模塊的 array 數(shù)組形式)。
可以向函數(shù) json.dumps()傳遞一些參數(shù)以控制轉(zhuǎn)換的結(jié)果。例如,參數(shù) sort_keys=True 時(shí),dict 類型的數(shù)據(jù)將按key(鍵)有序轉(zhuǎn)換:
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"]
即當(dāng) sort_keys=True 時(shí),轉(zhuǎn)換后的 json 串對于字典的元素是按鍵(key)有序的。
對于結(jié)構(gòu)化數(shù)據(jù),可以給參數(shù) indent 設(shè)置一個(gè)值(如 indent=3)來產(chǎn)生具有縮進(jìn)的、閱讀性好的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"
]
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注服務(wù)器之家的更多內(nèi)容!
原文鏈接:https://blog.csdn.net/m0_64430632/article/details/121598998