[PYTHON] Parse JSON file to object

Introduction

In python, you can easily parse JSON files with the standard json module, but it's a bit dict, so let's make it dot accessible.

Suddenly source code

#!/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" ]
  }
}

Commentary

--Pass ʻobject_hook to the json.loadmethod. --Inhook specified in ʻobject_hook, the keyword is expanded and distributed to the constructor of the prepared Json class. --In the Json class, each argument received by the keyword is added as an attribute.

Recommended Posts

Parse JSON file to object
Parse a JSON string written to a file in Python
Convert Tweepy Status object to JSON
[Introduction to Python] How to parse JSON
Script to generate directory from json file
How to create a JSON file in Python
Save the object to a file with pickle
json parse with gdb
How to read JSON
Convert json to excel
How to convert JSON file to CSV file with Python Pandas
Convert / return class object to JSON format in Python
How to convert Json file to CSV format or EXCEL format
Python script to create a JSON file from a CSV file
Try writing JSON format data to object storage Cloudian/S3
Convert Pascal VOC format xml file to COCO format json file
Convert HTML to text file
Upload a file to Dropbox
Display Japanese in JSON file
Convert genbank file to gff file
[Python] Convert CSV file uploaded to S3 to JSON file with AWS Lambda
[Python] Write to csv file with Python
Output to csv file with Python
Write standard output to a file
Output cell to file with Colaboratory
urllib3.exceptions.LocationParseError: Measures against Failed to parse
Python logging and dump to json
A light introduction to object detection
Easy to see difference of json
How to create a config file
File upload to Azure Storage (Python)
Try to extract specific data from JSON format data in object storage Cloudian/S3