2
1

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

Last updated at Posted at 2021-08-18

関数 結果
json.dumps(obj) 辞書型 -> 文字列(JSON)
json.loads(s) 文字列(JSON) -> 辞書型
json.dump(obj, fp) 辞書型 -> ファイル(JSON)
json.load(fp) ファイル(JSON) -> 辞書型
sample.py
import json

# 辞書型 -> 文字列(JSON)
def dict2json_str(json_dict):
    json_str = json.dumps(json_dict)
    print('dict2json_str -> ', type(json_str))
    return json_str

# 文字列(JSON) -> 辞書型
def json_str2dict(json_str):
    json_dict = json.loads(json_str)
    print('json_str2dict -> ', type(json_dict))
    return json_dict

# 辞書型 -> ファイル(JSON)
def dict2json_file(json_dict, filename):
    with open(filename, 'w') as f:
        json.dump(json_dict, f)
    print('dict2json_file -> ', filename)

# ファイル(JSON) -> 辞書型
def json_file2dict(filename):
    with open(filename, 'r') as f:
        json_dict = json.load(f)
    print('json_file2dict -> ', type(json_dict))
    return json_dict


json_file = 'sample.json'
sample_dict = {'title': 'json test'}
json_str = dict2json_str(sample_dict)       # 辞書型         -> 文字列(JSON)
json_dict = json_str2dict(json_str)         # 文字列(JSON)   -> 辞書型
dict2json_file(json_dict, json_file)        # 辞書型         -> ファイル(JSON)
result_dict = json_file2dict(json_file)     # ファイル(JSON) -> 辞書型
print(json_file, ' -> ', result_dict)

実行結果

dict2json_str ->  <class 'str'>
json_str2dict ->  <class 'dict'>
dict2json_file ->  sample.json
json_file2dict ->  <class 'dict'>
sample.json  ->  {'title': 'json test'}
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?