LoginSignup
6
3

More than 3 years have passed since last update.

Pythonでファイルに書き込まれたJSON文字列をパースする

Last updated at Posted at 2020-03-10

Pythonでファイルに書き込まれたJSON文字列をパースする方法を確認したのでメモ。

方法(json.load()

このようなファイルなら、

data.json
{
    "data":{
        "a": "こんにちは",
        "b": 123
    },
    "c": true
}

open()で取得したデータに対しjson.load()を利用すればJSONパースできる。

import json

raw = open('data.json', 'r')
type(raw)
# <class '_io.TextIOWrapper'>

parsed = json.load(raw)
type(parsed)
# <class 'dict'>

parsed
# {'data': {'a': 'こんにちは', 'b': 123}, 'c': True}

print(json.dumps(parsed, ensure_ascii=False, indent=4))
#{
#    "data":{
#        "a": "こんにちは",
#        "b": 123
#    },
#    "c": true
#}

駄目な方法(json.loads

  • json.loadsは、TextIOWrapperタイプのデータはパースできない。
json.loads(raw)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "/usr/lib64/python3.6/json/__init__.py", line 348, in loads
#     'not {!r}'.format(s.__class__.__name__))
# TypeError: the JSON object must be str, bytes or bytearray, not 'TextIOWrapper'

以上

6
3
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
6
3