-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparseJson.js
124 lines (115 loc) · 2.22 KB
/
parseJson.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
var parseJson = function(jsonStr){
var i= 0
var str = jsonStr
return parseValue()
function parseValue(){
if(str[i] === '{'){
return parseObject(str)
}else if(str[i] === '['){
return parseArray(str)
}else if(str[i] === 'n'){
return parseNull()
}else if(str[i] === 't'){
return parseTrue()
}else if(str[i] === 'f'){
return parseFalse()
}else if(str[i] ==='"'){
return parseString()
}else if(str[i] === ' ' || str[i] === ':'){
i++
return parseValue()
}else {
return parseNumber()
}
}
function parseObject(){
i++
var result = {}
while(str[i] != '}'){
while(str[i] !== '"'){
if(str[i] === '}') break
i++
}
if(str[i] === '}') break
var key = parseString()
var value = parseValue()
result[key] = value
if(str[i] === ','){
i++
}
}
i++
return result
}
function parseArray() {
i++
var result = []
while(str[i] != ']'){
result.push(parseValue())
if(str[i] === ','){
i++
}
}
i++
return result
}
function parseString(){
var result = ''
i++
while(str[i] != '"'){
result += str[i++]
}
i++
return result
}
function parseNull(){
var content = str.substr(i,4)
if(content === 'null'){
i += 4
return null
}else{
throw new Error('Unexpected char:' + i)
}
}
function parseTrue(){
var content = str.substr(i,4)
if(content === 'true'){
i += 4
return true
}else{
throw new Error('Unexpected char:' + i)
}
}
function parseFalse(){
var content = str.substr(i,5)
if(content === 'false'){
i += 5
return false
}else{
throw new Error('Unexpected char:' + i)
}
}
function parseNumber(){
var numStr = ''
while(isNumberChar(str[i])) {
numStr += str[i++]
}
return parseFloat(numStr)
}
function isNumberChar(c) {
var chars = {
'-' : true,
'+' : true,
'e' : true,
'E' : true,
'.' : true
}
if(chars[c]){
return true
}else if(c >= '0' && c <= '9'){
return true
}else{
return false
}
}
}