共計 629 個字符,預計需要花費 2 分鐘才能閱讀完成。
json.dumps()函數用于將 Python 對象編碼為 JSON 格式的字符串。它的使用方式如下:
import json
# 創建一個 Python 對象
data = {"name": "John",
"age": 30,
"city": "New York"
}
# 使用 json.dumps()將 Python 對象編碼為 JSON 格式的字符串
json_string = json.dumps(data)
# 打印編碼后的 JSON 字符串
print(json_string)
輸出結果:
{"name": "John", "age": 30, "city": "New York"}
你可以通過指定一些參數來定制編碼過程。例如,你可以使用 indent
參數來指定縮進的空格數量,使輸出的 JSON 字符串更易讀。示例如下:
import json
data = {"name": "John",
"age": 30,
"city": "New York"
}
# 使用 indent 參數指定縮進空格數量為 4
json_string = json.dumps(data, indent=4)
print(json_string)
輸出結果:
{
"name": "John",
"age": 30,
"city": "New York"
}
除了 indent
參數外,json.dumps()
函數還有其他一些可選參數,如 sort_keys
、separators
等,可以根據需求進行設置。詳細的使用方式可參考 Python 官方文檔中的 json.dumps()說明。
丸趣 TV 網 – 提供最優質的資源集合!
正文完