Guest User

r/badcode JSON writing (Python)

a guest
Mar 2nd, 2019
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. def toJson(obj):
  2.     string = False
  3.     escape = False
  4.     output = str(obj)
  5.     i = 0
  6.     add = 0
  7.     while True:
  8.        if i == len(str(obj)):
  9.         break
  10.        if str(obj)[i] == '{':
  11.         escape = False
  12.         output = output[0:i+add] + '{' + str(obj)[i+1:]
  13.        if str(obj)[i] == '}':
  14.         escape = False
  15.         output = output[0:i+add] + '}' + str(obj)[i+1:]
  16.        if str(obj)[i] == '[':
  17.         escape = False
  18.         output = output[0:i+add] + '[' + str(obj)[i+1:]
  19.        if str(obj)[i] == ']':
  20.         escape = False
  21.         output = output[0:i+add] + ']' + str(obj)[i+1:]
  22.        if str(obj)[i] == '"' and string == True:
  23.         escape = False
  24.         output = output[0:i+add] + '\\"' + str(obj)[i+1:]
  25.         add += 1
  26.        if str(obj)[i] == ':':
  27.         escape = False
  28.         output = output[0:i+add] + ':' + str(obj)[i+1:]
  29.        if str(obj)[i] == ',':
  30.         escape = False
  31.         output = output[0:i+add] + ',' + str(obj)[i+1:]
  32.        if str(obj)[i] == '\\' and escape == True:
  33.         escape = False
  34.         output = output[0:i+add] + '\\' + str(obj)[i+1:]
  35.        if str(obj)[i] == '\\' and escape == False:
  36.         escape = True
  37.         output = output[0:i+add] + '\\' + str(obj)[i+1:]
  38.        if output[i+add-3:i+add+1] == 'True' and string == False:
  39.         escape = False
  40.         output = output[0:i+add-3] + 'true' + str(obj)[i+1:]
  41.        if output[i+add-4:i+add+1] == 'False' and string == False:
  42.         escape = False
  43.         output = output[0:i+add-4] + 'false' + str(obj)[i+1:]
  44.        if output[i+add-3:i+add+1] == 'None' and string == False:
  45.         escape = False
  46.         output = output[0:i+add-3] + 'null' + str(obj)[i+1:]
  47.        if str(obj)[i] == '\'' and string == False:
  48.         escape = False
  49.         output = output[0:i+add] + '"' + str(obj)[i+1:]
  50.         string = True
  51.         i += 1
  52.         continue
  53.        if str(obj)[i] == '\'' and string == True and escape == False:
  54.         escape = False
  55.         string = False
  56.         output = output[0:i+add] + '"' + str(obj)[i+1:]
  57.        if str(obj)[i] == '\'' and string == True and escape == True:
  58.         escape = False
  59.         add -= 1
  60.         output = output[0:i+add] + '\'' + str(obj)[i+1:]
  61.        i += 1
  62.     return output
Advertisement
Add Comment
Please, Sign In to add comment