125 lines
2.5 KiB
Go
125 lines
2.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
)
|
|
|
|
type State int
|
|
|
|
const (
|
|
Initial State = iota
|
|
ObjectStart
|
|
ObjectKey
|
|
ObjectKeyValueSeparator
|
|
ObjectValueString
|
|
ObjectValueObject
|
|
ObjectValueArray
|
|
ObjectValueNumber
|
|
ObjectValueTrue
|
|
ObjectValueFalse
|
|
ObjectValueNull
|
|
ObjectEnd
|
|
ArrayStart
|
|
ArrayValue
|
|
ArrayEnd
|
|
)
|
|
|
|
type JSONParser struct {
|
|
state State
|
|
stack []interface{}
|
|
key string
|
|
value interface{}
|
|
}
|
|
|
|
func NewJSONParser() *JSONParser {
|
|
return &JSONParser{
|
|
state: Initial,
|
|
}
|
|
}
|
|
|
|
func (p *JSONParser) parse(char byte) {
|
|
stateTable := []func(byte){
|
|
Initial: p.handleInitial,
|
|
ObjectStart: p.handleObjectStart,
|
|
ObjectKey: p.handleObjectKey,
|
|
ObjectKeyValueSeparator: p.handleObjectKeyValueSeparator,
|
|
// 类似地,定义其他状态的处理函数...
|
|
ObjectValueString: p.handleOther,
|
|
ObjectValueObject: p.handleOther,
|
|
ObjectValueArray: p.handleOther,
|
|
ObjectValueNumber: p.handleOther,
|
|
ObjectValueTrue: p.handleOther,
|
|
ObjectValueFalse: p.handleOther,
|
|
ObjectValueNull: p.handleOther,
|
|
ObjectEnd: p.handleOther,
|
|
ArrayStart: p.handleOther,
|
|
ArrayValue: p.handleOther,
|
|
ArrayEnd: p.handleOther,
|
|
}
|
|
|
|
stateTable[p.state](char)
|
|
}
|
|
|
|
func (p *JSONParser) handleInitial(char byte) {
|
|
if char == '{' {
|
|
p.state = ObjectStart
|
|
p.stack = append(p.stack, make(map[string]interface{}))
|
|
} else if char == '[' {
|
|
p.state = ArrayStart
|
|
p.stack = append(p.stack, []interface{}{})
|
|
}
|
|
}
|
|
|
|
func (p *JSONParser) handleObjectStart(char byte) {
|
|
if char == '}' {
|
|
p.state = ObjectEnd
|
|
} else {
|
|
p.state = ObjectKey
|
|
// 解析键
|
|
}
|
|
}
|
|
|
|
func (p *JSONParser) handleObjectKey(char byte) {
|
|
if char == ':' {
|
|
p.state = ObjectKeyValueSeparator
|
|
}
|
|
// 解析键
|
|
}
|
|
|
|
func (p *JSONParser) handleObjectKeyValueSeparator(char byte) {
|
|
switch char {
|
|
case '"':
|
|
p.state = ObjectValueString
|
|
case '{':
|
|
p.state = ObjectValueObject
|
|
case '[':
|
|
p.state = ObjectValueArray
|
|
case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
|
|
p.state = ObjectValueNumber
|
|
case 't':
|
|
p.state = ObjectValueTrue
|
|
case 'f':
|
|
p.state = ObjectValueFalse
|
|
case 'n':
|
|
p.state = ObjectValueNull
|
|
}
|
|
// 其他情况下,忽略字符(例如空格、换行符等)
|
|
}
|
|
|
|
func (p *JSONParser) handleOther(char byte) {
|
|
fmt.Printf("other: %c\n", char)
|
|
}
|
|
|
|
// 类似地,定义其他状态的处理函数...
|
|
|
|
func main() {
|
|
parser := NewJSONParser()
|
|
json := `{"key": "value"}`
|
|
|
|
for _, char := range json {
|
|
parser.parse(byte(char))
|
|
}
|
|
|
|
fmt.Println(parser.stack)
|
|
}
|