1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PythonでJSONファイルの読み書き

Posted at

Pythonのjsonモジュールを使用するとJSON形式のファイルや文字列を辞書(dict)などのオブジェクトとして受け取ることができる。

#1.JSON文字列を辞書に変換
json.loads()関数を使用する。


s = r'{"C": "\u3042", "A": {"i": 1, "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]}'

print(s)
# {"C": "\u3042", "A": {"i": 1, "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]}

d = json.loads(s)

print(d)
# {'A': {'i': 1, 'j': 2}, 'B': [{'X': 1, 'Y': 10}, {'X': 2, 'Y': 20}], 'C': 'あ'}

print(type(d))
# <class 'dict'>

#2.JSONファイルを辞書として読み込み
json.load()関数を使用する。

with open('/test.json') as f:
    print(f.read())
# {"C": "\u3042", "A": {"i": 1, "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]}

#3.辞書をJSON文字列にして出力
json.dumps()関数を使用する。

d = {'A': {'i': 1, 'j': 2}, 
     'B': [{'X': 1, 'Y': 10}, 
           {'X': 2, 'Y': 20}], 
     'C': ''}

sd = json.dumps(d)

print(sd)
# {"A": {"i": 1, "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}], "C": "\u3042"}

print(type(sd))
# <class 'str'>

#4.辞書をJSONファイルとして保存
json.dump()関数を使用。


d = {'A': {'i': 1, 'j': 2}, 
     'B': [{'X': 1, 'Y': 10}, 
           {'X': 2, 'Y': 20}], 
     'C': ''}


with open('/test.json', 'w') as f:
    json.dump(d, f, indent=4)
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?