另一個常見的格式是 JSON (JavaScript Object Notation) ,可以想成是 Python 的 dict list 。Python 也有提供 標準的模組 來處理 JSON 格式的資料,這邊也介紹幾個常用到的 API。

一樣到 Mockaroo 來產資料,這次在 Format 的選項要選擇 JSON

  • 反序列化(decode)
  • json 模組提供兩個方法來反序列化(讀取) JSON 格式的資料,兩個方法只差在第一個參數,其他的參數都一樣:

    json.load :第一個參數需要支援 .read() 方法(通常是 文字檔案 二進位檔案 實例)用來讀取資料。 json.loads :第一個參數是 str bytes bytearray 實例。

    反序列化時會依照下列表格,將 JSON 的資料型態轉換為 Python 的資料型態:

    Python
    import json
    with open('mock_data.json', newline='') as jsonfile:
        data = json.load(jsonfile)
        # 或者這樣
        # data = json.loads(jsonfile.read())
        print(data)
    
  • 序列化(encode)
  • json 模組也提供兩個方法來序列化(寫入) JSON 格式的資料,第一個參數都是要序列化的目標,兩個方法只差在第二個參數,其他的參數都一樣:

    json.dump:第二個參數需要支援 .write() 方法(通常是文字檔案二進位檔案實例)用來寫入資料。 json.dumps:不需要第二個參數,會直接回傳 JSON 格式的 str 實例。

    序列化時會依照下列表格,將 Python 的資料型態轉換為 JSON 的資料型態:

    Python
    import json
    with open('mock_data.json', newline='') as jsonfile:
        data = json.load(jsonfile)
    with open('mock_data.json', 'w', newline='') as jsonfile:
        data.append({ \
            'id': 5, \
            'first_name': 'Vin', \
            'last_name': 'Sturdgess', \
            'gender': 'Male', \
            'country': 'Greece' \
        json.dump(data, jsonfile)
        # 或者這樣
        # jsonfile.write(json.dumps(data))
    

    不知道有沒有人發現, 序列化後的字串是沒有排版的,如果閱讀上有需要排版的話,可以在序列化時加上參數來處理。

    json.dump(data, jsonfile) 換成 json.dump(data, jsonfile, indent=4),執行後再比較一下差別。

    但排版後會增加儲存所需的空間跟傳輸量,通常是不建議在儲存時做排版的。

    json — JSON encoder and decoder — Python 3.7.4 documentation