【Python JSON 處理 #1】python json 使用範例,產生 json 檔案的範本 python json template

前言

json 算是檔案與檔案溝通之間,非常經常使用的格式,
由於非常經常使用,我們將 json 製作檔案的格式紀錄下來,
供之後反覆使用方便。

範例程式碼

下面的範例是我們新增一份以 timestamp 作為檔案名稱的 json 檔案。

其他相關的變數:

  • root_folder:檔案根目錄
  • generate_jsonfile(file_name, json_content):產生對應的 json 檔案
  • make_json():json 的內容設定
import json
import time

root_folder = './'

def generate_jsonfile(file_name, json_content):

    print(f"generating file: {file_name}")
    with open(file_name, 'w') as f_out:
        ret = json.dumps(json_content)
        f_out.write(ret)

def make_json():
    tmp_ljob = {}
    tmp_ljob["key1"] = "value1"
    tmp_ljob["key2"] = "value2"
    tmp_ljob["key3"] = "value3"

    return tmp_ljob

if __name__ == '__main__':
    current_timestamp = int(time.time() * 1000) # 13 digits
    file_name = root_folder + "{:13d}.json".format(current_timestamp)
    json_content = make_json()

    generate_jsonfile(file_name, json_content)

Reference