D
D
Dmitry Laptiev2019-06-21 14:33:36
Python
Dmitry Laptiev, 2019-06-21 14:33:36

Parse json file and make it available after initialization?

Hello, I have been learning python for a couple of days. The question is:
I have a json config file. There is a base class that also collects information from configs. How can I, after initialization, store information somewhere without parsing this file again. I would like to import this class and just refer to it as an array. How to do it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Astrohas, 2019-06-21
@dmitrykorj

The pattern is called a singleton.

class EnvironmentSetup(unittest.TestCase):
    base_config = None

    @classmethod
    def setUpClass(cls):
        cls.base_config = cls.setConfig()

    @classmethod
    def setConfig(cls):
        with open('../config.json') as file:
            config = json.load(file)
        return config

    def __new__(cls):
        # Перекрываем создание объекта класса
        if not hasattr(cls, 'instance'):
            cls.instance = super().__new__(cls)
        return cls.instance

tu and at init do all things

A
Alexander, 2019-06-21
@NeiroNx

You probably parse it with regular expressions, while all normal people use the json library.
the function just parses it into a variable of type dict or list (it depends on the content) and then you access it as a dictionary array.config=json.load(open("config.json"))

>>>config["myint"]
1
>>>config["mystring"]
'string'
>>>config["myarray"][0]
'item1'

you can parse into a variable that is visible in all functions and then access it.
PS I store local mini databases in json - if you want to download, process, save. Very comfortably.

D
Dmitry Laptiev, 2019-06-21
@dmitrykorj

Class 1 (initializing)

class EnvironmentSetup(unittest.TestCase):
    base_config = None

    @classmethod
    def setUpClass(cls):
        cls.base_config = cls.setConfig()

    @classmethod
    def setConfig(cls):
        with open('../config.json') as file:
            config = json.load(file)
        return config

Class 2
from tests.base.test import EnvironmentSetup as base_test
class Another:
    def __init__(self, params):
        print(base_test.base_config)  -> Получаю None соответственно

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question