The problem
I have a few JSON Files which are built different and I need a code to be able to edit a value as well in the dicts which are just one dict and others who have nested dicts without removing other values.
Examples
So I got for example one JSON File which is like this:
JSON/id_list.json
{"whatever": [ID_1, ID_2, ID_3]}
JSON/main_id.json
{"value": "yes"}
or another on like this
JSON/id_data.json
{"data": {"ID_1": {"type1": 0, "type2": 1}, "ID_2": {"type1": 0, "type2": 0}}}
Current Code
My current code is only able to edit the first and / or second so I wanted it to be general but just didn't seem to find an answer
Functions/get_json.py
def get(name: str, path: str, load: bool):
if load:
_load(path)
return loadedf[name]
def update(name: str, text, path: str, load: bool):
if load:
_load(path)
loadedf[name].remove(get(name, path, False))
loadedf[name].append(text)
with open(path, "w+"):
json.dump(loadedf, nfl)
def _load(path: str):
preloadf = open(path, 'r')
global loadedf
loadedf = json.load(preloadf)
game.py
from Functions import get_json.py
async def random_function():
get_json.get('whatever', '/JSON/id_list.json', True)
get_json.update('value', 'no', '/JSON/main_id.json', True)
New Code Idea
game_new.py
from Functions import get_json.py
async def random_function():
get_json.get(['whatever'], '/JSON/id_list.json', True)
get_json.get(['data', 'ID_1', 'type2'], '/JSON/id_data.json', True)
get_json.update(['data', 'ID_2', 'type1'], '/JSON/id_data.json', False)
But I have no Idea how to do or realize this.
What I tried so far
I tried dict.update()
, doing it with for loops like
prev = loadedf
for i in name:
prev = prev[i]
prev.remove(get(name, path, False)[0])
or with some weird stuff like __setattr()__
and with a way with which I wasn't happy as it can't handle JSONs generally and was really long and complicated;
I tried to do it with the optional parameters deep
, name2
and name3
and do it with an if elif
to do if deep == 2: return loadedf[name][name2]
.
The code used here might be outdated from what I had or partly not working as I wrote it completely new because I rewrote it a few times to reach my goal; to be generally able to do all this with JSON Files.