LoginSignup
8
6

More than 5 years have passed since last update.

JSONファイルをオブジェクトにパースする

Posted at

はじめに

pythonでは標準のjsonモジュールで簡単にJSONファイルをパースできますが、dictになってしまうのがちょっとアレなので、ドットアクセスできるようにしてみます。

いきなりソースコード

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json

class Json(object):
    def __init__(self, **kwargs):
        [setattr(self,k,v) for k,v in kwargs.items()]

def hook(dct):
    return Json(**dct)

def load(filename):
    with open(filename) as f:
        obj = json.load(f, object_hook=hook)
    return obj


if __name__ == '__main__':
    config = load('config.json')
    print(config.conf_1)            # conf_1
    print(config.conf_2.conf_21[0]) # conf_221
config.json
{
  "conf_1" : "conf_1",
  "conf_2" : {
    "conf_21" : "conf_21",
    "conf_22" : [ "conf_221", "conf_222" ]
  }
}

解説

  • json.load メソッドに object_hook を渡します。
  • object_hookに指定した hook では、用意した Json クラスのコンストラクタに、キーワードを展開して横流しします。
  • Json クラスでは、キーワードで受け取った各引数を、アトリビュートとして追加します。
8
6
2

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