Home > Software design >  Get value from JSON collection starting from specific base?
Get value from JSON collection starting from specific base?

Time:11-04

How would I get the value of a variable stored in a JSON file under a specific base / category using the existing solution below?

This is a class that takes JSON and stores it in a collection originally from Multipurpose function to create and append json using specified base python

import json
import os

class data_manager():
    BASE_COLLECTIONS_FOLDER = "./data"

    def __init__(self, collection_name):
        self.collection_name = collection_name
        self.collection_file_path = (
                        f"{self.BASE_COLLECTIONS_FOLDER}/{self.collection_name}.json")
        self.collection = {}
        self.ensure_collection()
        self.load_collection()

    def ensure_collection(self):
        if os.path.isfile(self.collection_file_path):
            return

        os.makedirs(self.BASE_COLLECTIONS_FOLDER, exist_ok=True)
        self.save_collection()

    def load_collection(self):
        with open(self.collection_file_path, "r", encoding="utf-8") as collection_file:
            self.collection = json.load(collection_file)[self.collection_name]

    def save_collection(self):
        with open(self.collection_file_path, "w", encoding="utf-8") as collection_file:
            json.dump({self.collection_name: self.collection}, collection_file, indent=4)

    def write_to_json(self, data, key=None):
        if not key:
            self.collection = {**self.collection, **data}
        else:
            self.collection[key] = {**self.collection.get(key, {}), **data}
        self.save_collection()

people = data_manager("twitch")

streamer_information = {'streamer_username':None, 'streamer_username': None,
                        'streamer_game': None, 'streamer_uptime': None,
                        'streamer_viewers': None}

self.data.write_to_json({self.streamer_username: {}})
self.data.write_to_json(
                {"online": self.online,
                 "streamer_title": self.streamer_information['streamer_title'],
                 "streamer_game": self.streamer_information['streamer_game'],
                 "streamer_uptime": self.streamer_information['streamer_uptime'],
                 "streamer_viewers": self.streamer_information['streamer_viewers']},
                self.streamer_username)

For example, my JSON file looks like this:

{
    "twitch": {
        "trainwreckstv": {
            "online": true,
            "streamer_title": "18  give us 1 f'in w ffs #ad | !twitter | !youtube | !podcast",
            "streamer_game": "Slots",
            "streamer_uptime": "18:40:53",
            "streamer_viewers": "24,922"
        },
        "mizkif": {
            "online": true,
            "streamer_title": "(DAY 2) NNN  - WHO WAS IN MY ROOM LAST NIGHT? MARIO PARTY LATER  | !pobox",
            "streamer_game": "Just Chatting",
            "streamer_uptime": "4:39:47",
            "streamer_viewers": "45,400"
        }
    }
}

How would I get the value of "streamer_title" starting from a specific base (ex mizkif or trainwreckstv)?

It would be nice if I could possibly do people.get_value(key, base) where key is the key and base is the category to start the search from.

For example:

people.get_value('streamer_title','mizkif')

could return:

"(DAY 2) NNN  - WHO WAS IN MY ROOM LAST NIGHT? MARIO PARTY LATER  | !pobox"

CodePudding user response:

To get the value "streamer_title" from "mizkif", you need to use the [] like with a dictionary.

people["mizkif"]["streamer_title"]

CodePudding user response:

Here's how to implement that "nice method".
Note I changed the name of class to conform to the PEP 8 Naming Conventions.

import json
import os

class DataManager:
    BASE_COLLECTIONS_FOLDER = "./data"

    def __init__(self, collection_name):
        self.collection_name = collection_name
        self.collection_file_path = (
            os.path.join(self.BASE_COLLECTIONS_FOLDER, self.collection_name ".json"))
        self.collection = {}
        self.ensure_collection()
        self.load_collection()

    def get_value(self, key, base):  # ADDED METHOD
        return self.collection[self.collection_name][base][key]

    def ensure_collection(self):
        if os.path.isfile(self.collection_file_path):
            return

        os.makedirs(self.BASE_COLLECTIONS_FOLDER, exist_ok=True)
        self.save_collection()

    def load_collection(self):
        with open(self.collection_file_path, "r", encoding="utf-8") as collection_file:
            self.collection = json.load(collection_file)  #[self.collection_name]

    def save_collection(self):
        with open(self.collection_file_path, "w", encoding="utf-8") as collection_file:
            json.dump({self.collection_name: self.collection}, collection_file, indent=4)

    def write_to_json(self, data, key=None):
        if not key:
            self.collection = {**self.collection, **data}
        else:
            self.collection[key] = {**self.collection.get(key, {}), **data}
        self.save_collection()


if __name__ == '__main__':
    people = DataManager("twitch")

    print("people.get_value('streamer_title', 'mizkif') ->")
    print(f"    {people.get_value('streamer_title', 'mizkif')!r}")

Output:

people.get_value('streamer_title', 'mizkif') ->
    '(DAY 2) NNN  - WHO WAS IN MY ROOM LAST NIGHT? MARIO PARTY LATER  | !pobox'
  • Related