Python 寫入 JSON 檔案

本篇 ShengYu 介紹 Python 寫入 JSON 檔案的方法,

Python 把 JSON 寫入到檔案

Python 在寫入 JSON 前要先 import json 模組,然侯開檔,接著將開檔完的 File 物件 f 傳給 json.dump() 第二個參數,第一個參數會輸出的 dict 變數,

python3-json-write.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json

d = {
"name": "Sam",
"age": 26,
"married": True,
"city":"Berlin",
"languages": ["English", "Dutch"]
}

with open('output.json', 'w') as f:
json.dump(d, f)

輸出的 JSON 檔案內容長這樣,

data.json
1
{"married": true, "name": "Sam", "age": 26, "languages": ["English", "Dutch"], "city": "Berlin"}

下一篇介紹 讀取 json 檔案

其它相關文章推薦
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python 新手入門教學懶人包
Python 寫檔,寫入 txt 文字檔
Python 讀取 csv 檔案
Python 寫入 csv 檔案
Python 字串分割 split
Python 取代字元或取代字串 replace
Python 讓程式 sleep 延遲暫停時間
Python 產生 random 隨機不重複的數字 list
Python PyAutoGUI 使用教學
Python OpenCV resize 圖片縮放