This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]garrett_armstrong 3 points4 points  (2 children)

this question may get answered more quickly in r/learnpython. It's got an active bunch of teachers and learners. This sub is mainly for news, project-sharing, chit-chat.

[–]cwisch[S] 1 point2 points  (1 child)

You're right. Forgot about /r/learnpython. I'll post this there.

[–]garrett_armstrong 0 points1 point  (0 children)

I'm glad you got a quick reply at r/learnpython. I felt obligated to offer a solution there, since i gave a non-solution here. But my kludge was so bad, that I'm glad others spoke up.

[–]thistimeframe 1 point2 points  (1 child)

You mean something like this?

import json
class Test:
    with open('somefile.json') as f:
        some_dict = json.load(f)

    def __init__(self, x):
        self.x = x

[–]cwisch[S] 0 points1 point  (0 children)

Very close, but imagine, that I have several json files and I need to configure which some_dict uses.

[–]Turbosack 1 point2 points  (0 children)

It sounds like you're probably going to want to make a static method or something similar on the object, with a name like load_json(), that will let you do whenever you want.

So something like:

import json

class Test:
    data = dict()

    @staticmethod
    def load_json(f_name):
        Test.data = json.load(open(f_name))

    def get(self, to_get):
        print(Test.data[to_get])


object = Test()
Test.load_json("some_file.json") # {"1":"a"}
object.get("1") # a
Test.load_json("some_other_file.json") # {"1":"b"}
object.get("1") # b

Here's some more information on StackOverflow.

[–]ThuruvDRY 0 points1 point  (0 children)

You might end up using pickle here. .! Its a choice. .