0
Hello, I have a problem that is the following I have a map with the following format and I need to create a script that converts this map to a specific JSON model in python:
Map template:
TELEFONIA
+ CELULAR
+ CORRETOR
+ a
~ CANCELAR LINHA
~ SOLICITAR LINHA
~ b
+ aba
~ CANCELAMENTO DE LINHA
~ CANCELAMENTO DE MODEM
+ CMS
~ ALTERAR
Model of JSON:
{
"label" : "TELEFONIA",
"valor":[
{"label" : "CELULAR", "valor":[
{"label" : "CORRETOR", "valor":[
{"label" : "a", "valor":[
{"label" : "CANCELAR LINHA" },
{"label" : "SOLICITAR LINHA" },
]}
]},
{"label" : "b" },
{"label" : "aba", "valor":[
{"label" : "CANCELAMENTO DE LINHA" },
{"label" : "CANCELAMENTO DE MODEM" },
]},
]},
{"label" : "CMS", "valor" :[
{"label" : "ALTERAR" },
]}
]
}
A code I made (But I’ve deleted enough):
text = 'TELEFONIA\n\t+ CELULAR\n\t\t+ CORRETOR\n\t\t\t+ a\n\t\t\t\t~ CANCELAR LINHA\n\t\t\t\t~ SOLICITAR LINHA\n\t\t~ b\n\t\t+ aba\n\t\t\t~ CANCELAMENTO DE LINHA\n\t\t\t~ CANCELAMENTO DE MODEM\n\t+ CMS\n\t\t~ ALTERAR'
nivelAnterior = 0
def createTree(text):
e = []
for line in text.split("\n"):
# valor = (line.split("~ ")[1] if nivelAnterior == line.count('\t'))
if "+" in line:
valor = line.split("+ ")[1]
elif "~" in line:
valor = line.split("~ ")[1]
else:
valor = line
e.append({"nivel":line.count('\t'),"valor": valor})
return e
def a(val):
pai = 0
prev = 0
listOfChild = []
listOfObjs = []
valuePai = ""
i = 0
for value in val:
nivel = value["nivel"]
if nivel > prev:
# child
pai = prev
elif nivel == prev:
# bro
pai = pai
elif nivel < prev:
# parent
pai += nivel - prev
prev = nivel
print("\nvalor atual: ",value["valor"])
print("\t",listOfChild)
print('\n\t',listOfObjs)
val = createTree(text)
# print(val)
a(val)
I didn’t understand the logic to have appeared this
aba
in the middle of JSON, and I believe it should be just onea
, no? you need to create a parser template, because all logic is based on the indentations of your file, and to know what is inside what. I would create a function to create a level and use a recurring function, which is called if + appears next to the element.– Luan Naufal
Show what you’ve tried to do so far, because the idea of Stack Overflow is to help with code questions, not write code for others.
– Luan Naufal
@Luannaufal, it was my own mistake I corrected
– Lucas Avelino
@Luannaufal already put some of the codes I’ve done here
– Lucas Avelino
for what I understand, when there is no sign of
+
or~
, I understand that logic is the same as when it appears+
, in the case of the first element, that is, it adds the "value" as the next element on the same level, which is a list. And the lists only have one element and no more]. The logic is not simple, but I’ll see if I take the time to assemble something here– Luan Naufal