Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. source = """
  2. {
  3. "root1"
  4. {
  5. "item1" "1"
  6. "item2" "abc"
  7.  
  8. "item3"
  9. {
  10. "cell"
  11. {
  12. "cell1"
  13. {
  14. "cell1Name" "99"
  15. }
  16. "cell2"
  17. {
  18. "cell2Name" "cdb"
  19. }
  20. }
  21. }
  22.  
  23. "item4" "valueI"
  24. }
  25.  
  26. "root2"
  27. {
  28. "item1" "88"
  29. "item2" "tg"
  30.  
  31. "item3"
  32. {
  33. "cell"
  34. {
  35. "cell1"
  36. {
  37. "cell1Name" "99"
  38. }
  39. "cell2"
  40. {
  41. "cell2Name" "ujh"
  42. }
  43.  
  44. }
  45. }
  46.  
  47. "item4" "valueb"
  48. }
  49. }
  50. """
  51.  
  52. i = 0
  53. LP=1
  54. RP=2
  55. def nextToken():
  56. global i
  57. while i < len(source) and source[i].isspace():
  58. i += 1
  59. if source[i] == '{':
  60. i += 1
  61. return LP
  62. if source[i] == '}':
  63. i += 1
  64. return RP
  65. if source[i] == '"':
  66. start = i
  67. i += 1
  68. while i < len(source) and source[i] != '"':
  69. i += 1
  70. if i < len(source):
  71. i += 1
  72. return source[start+1:i-1]
  73. else:
  74. raise Exception('expect "')
  75. raise Exception('expect {}"')
  76.  
  77.  
  78.  
  79.  
  80. def parseValue():
  81. nt = nextToken()
  82. if nt == LP:
  83. return parseObject()
  84. if nt == RP:
  85. raise Exception('expect { or string')
  86. return nt
  87.  
  88. def parseObject():
  89. obj = {}
  90. while True:
  91. nt = nextToken()
  92. if nt == RP:
  93. return obj
  94. if nt == LP:
  95. raise Exception('expect string')
  96. k = nt
  97. v = parseValue()
  98. obj[k] = v
  99. return obj
  100.  
  101. print(parseValue())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement