1

I'm trying to create my own JSON formatter in python (yes, i know there are already libraries out there, this is a challenge for myself).

userinput = []
askuser = input("Enter your JSON:\n")

for i in askuser:
    userinput.append(i)

for j in userinput:
    if '{' in userinput:
        userinput.insert(userinput.index('{') +1, '\n')
        userinput.insert(userinput.index('\n') +1, '\t')
    else:
        pass
    if '}' in userinput:
        userinput.insert(userinput.index('}') -0, '\n')
    else:
        pass
    if ',' in userinput:
        userinput.insert(userinput.index(',') +1, '\n')
        userinputString = ''.join(userinput)
    else:
        pass

print(userinputString)

I tried this without looping through, it works, but only when the condition becomes true for the first time. If there are multiple curly brackets, which there usually is in JSON. then this will only format the first one.

My question is... does anyone know why my code just freezes when I input a sample JSON such as this:

{"name":"John", "age":30, "car":null}

Is it due to python just being slow, or am I missing something? (probably the latter)

I notice I'm trying to perform 3 conditional computations on each character in my list, so the bigger it gets the slower it will become, so if this is python I will probably try to write this in C instead, and then make it accessible to python via libraries.

noobi3
  • 40
  • 8
  • 4
    In general it's a bad idea to modify a list while looping over it. – Mark Dec 30 '21 at 19:52
  • https://stackoverflow.com/questions/4929251/how-to-step-through-python-code-to-help-debug-issues – mkrieger1 Dec 30 '21 at 19:53
  • @Mark If this is bad practice what would better practice be? should I save the results onto a new list instead? – noobi3 Dec 30 '21 at 19:56
  • 1
    Hint: You are currently not using `j` for anything. It should be used somehow. Think about how it should be used. – mkrieger1 Dec 30 '21 at 20:01
  • 2
    @noobi3 yes a new list would be a better approach. Also, you don't need to use `if '{' in userinput:` on every iteration of the loop. You are already looping through the string. You should check if `j == '{'`, etc... Having said that, this approach is probably doomed once you start getting more complicated nested json. – Mark Dec 30 '21 at 20:02
  • 1
    I would also like to point out that each of your if clauses will result in True, since there is always a '{', and '}' and a ',' in your input. they are really serving no useful purpose. – itprorh66 Dec 30 '21 at 20:35

0 Answers0