How to create a file-based JSON map

Asked

Viewed 187 times

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 one a, 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.

  • 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.

  • @Luannaufal, it was my own mistake I corrected

  • @Luannaufal already put some of the codes I’ve done here

  • 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

1 answer

1


SOLUTION:

After rethinking all logic I arrived at the following solution:

map = open("MAPA CATEGORIAS.MAP",encoding="utf8").read()

def getListOfChild(listOfElements, fatherIndex):
    i = fatherIndex + 1
    ret = []
    for element in listOfElements:
        if listOfElements[fatherIndex].count("#") < listOfElements[i].count("#"):
            ret.append({"lineIndex":i,"label":listOfElements[i]})
        else:
            break;
        i += 1
    print("getListOfChild:",ret)
    return ret;
def getListOfExp(mapGeral,fatherIndex):
    expd = []
    i = fatherIndex
    father = {"fatherIndex":fatherIndex,"fatherLevel":mapGeral[fatherIndex].count("#")}
    map = getListOfChild(mapGeral, fatherIndex)
    for line in map:
        print(line["label"])
        print(("#"*(father["fatherLevel"]+1))+"+")
        if line["label"].startswith(("#"*(father["fatherLevel"]+1))+"+"):
            line["valor"] = getListOfExp(mapGeral,line["lineIndex"])
            expd.append(line)
        elif line["label"].startswith(("#"*(father["fatherLevel"]+1))+"~"):
            expd.append(line)
    return expd

map = map.split("\n")
print(map[1].count("#"))
open("result.json","w+",encoding="utf-8").write(str(getListOfExp(map,208)).replace('\'','"').replace('#','').replace('+ ','').replace('~ ',''))

ps: the code is already linked the way I needed to read and write files,

Thanks for the support,

  • I just don’t understand where that came from # that wasn’t in the initial description of your code, @Lucasavelino. I put together a piece of the code to solve this, but it still needs to debug the ending, because by lowering the level, it was not printing in the final Json. But if you solved your problem, that’s great!

  • @Luannaufal I was having string comparison problems with t ai I decided to replace all t, to remedy my problem!

  • great! important that managed to solve. Good luck

Browser other questions tagged

You are not signed in. Login or sign up in order to post.