3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PickleとJsonの比較 【ファイル形式、互換性、...】

3
Posted at

はじめに

Pythonでオブジェクトを保存するとき、みなさんはどうしていますか?
実は、PythonにはJSONだけではなくPickleと呼ばれるものもあります。
今回は、その二つを比較してみましょう!

JSON

JSONはさまざまなプログラミング言語で使用できる記法です。

{
    "文字列": "値",
    "数字": -0.12,
    "真偽値": true,
    "配列": ["hello" "world"],
    "null": null
}

Javascriptをはじめ、Ruby、Java、C#、もちろん
Pythonでも利用できます。

import json

# Pythonの辞書型からJSONの文字列に変換する
dumped_json = json.dumps({"content": "hello world"})
print(type(dumped_json)) # <class 'str'>

# JSONの文字列からPythonの辞書型に変換する
loaded_json = json.loads(dumped_json)

print(type(loaded_json)) # <class 'dict'>
print(loaded_json["content"]) # hello world

Pickle

Pickleは、Pythonのオブジェクトをbytes型と相互変換します。
Pythonオブジェクトなので、他のプログラミング言語では
使用することができません。

from collections import namedtuple
import pickle

ContentType = namedtuple("ContentType", ['content'])

# PythonオブジェクトからPickleに変換する
dumped_pickle = pickle.dumps(ContentType("hello world"))
print(type(dumped_pickle)) # <class 'bytes'>

# PickleからPythonオブジェクトに変換する
loaded_pickle: ContentType = pickle.loads(dumped_pickle)
print(type(loaded_pickle)) # <class '__main__.ContentType'>
print(loaded_pickle.content) # hello world

比較表

観点/形式 JSON Pickle
dump後の型 str bytes
互換性 さまざまな
プログラミング言語で
使用可能
Pythonのみ
カスタムクラス dictにしてからdump そのままdump可能
拡張子 .json .pkl

最後まで読んでいただきありがとうございます!

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?