Всем привет.
Пишу свой скрипт для работы с json.
def addGroup(file_path, group_id = None):
new_group_name = input("Enter group name: ")
if new_group_name != "":
group_slug = new_group_name.lower().replace(" ", "_")
if sectionHasGroup(file_path, group_slug):
print(colored("Group already exists!!!", "red"))
return
with open(file_path, 'r') as file:
# read
data = json.load(file)
if group_id:
group_path = getGroupPathById(file_path, group_id)
new_tab = newTab(new_group_name)
group_path.append(new_tab)
new_group = newGroup(new_group_name)
group_path.append(new_group)
newData = json.dumps(data, indent=4)
print(json.dumps(group_path, indent=4))
else:
new_tab = newTab(new_group_name)
data[0]['fields'].append(new_tab)
new_group = newGroup(new_group_name)
data[0]['fields'].append(new_group)
newData = json.dumps(data, indent=4)
print(json.dumps(data[0]['fields'], indent=4))
print(newData)
Если в addGroup передаю group_id, то нужно в json в нужном месте вставить код.
group_path = getGroupPathById(file_path, group_id)
И функция, которая возварщает путь
import json
def getGroupPathById(file_path, group_id):
full_path = '';
f = open(file_path,)
data = json.load(f)
for i in data:
for j in i['fields']:
if j['type'] == "group":
if j['key'] == group_id:
index = i['fields'].index(j)
full_path = f"data[0]['fields'][{index}]"
else:
for k in j['sub_fields']:
if k['type'] == "group":
if k['key'] == group_id:
index = j['sub_fields'].index(k)
full_path = f"data[0]['fields'][{i['fields'].index(j)}]['sub_fields'][{index}]"
else:
for l in k['sub_fields']:
if l['type'] == "group":
if l['key'] == group_id:
index = k['sub_fields'].index(l)
full_path = f"data[0]['fields'][{i['fields'].index(j)}]['sub_fields'][{j['sub_fields'].index(k)}]['sub_fields'][{index}]"
print(f"full_path: {full_path}")
return full_path
В addGroup вот тут ошибка
group_path.append(new_tab)
Заранее благодарен.