Ejemplo n.º 1
0
func (parser *Parser) parseArray(parent *value.JSONValue) error {
	firstToken, err := parser.tokenizer.NextToken()
	if err != nil {
		return err
	}
	if !firstToken.IsEqualTo(token.NewTokenBeginArray()) {
		return fmt.Errorf("%#v is invalid begin array token", firstToken)
	}
	parent.ArrayValue = make([]value.JSONValue, 0)
	for {
		peekedToken, err := parser.tokenizer.PeekToken(0)
		if err != nil {
			return err
		}
		if peekedToken.IsEqualTo(token.NewTokenEndArray()) {
			parser.tokenizer.NextToken()
			break
		}
		itemValue := value.NewJSONValue()
		err = parser.parseValue(&itemValue)
		if err != nil {
			return err
		}
		parent.ArrayValue = append(parent.ArrayValue, itemValue)

		maybeComma, err := parser.tokenizer.PeekToken(0)
		if err == nil && maybeComma.IsEqualTo(token.NewTokenComma()) {
			parser.tokenizer.NextToken()
			continue
		}
	}
	return nil
}
Ejemplo n.º 2
0
// Parse parses JSON.
func (parser *Parser) Parse() (value.JSONValue, error) {
	firstToken, err := parser.tokenizer.PeekToken(0)
	if err != nil {
		return value.NewJSONValue(), err
	}
	if firstToken.IsEqualTo(token.NewTokenBeginObject()) {
		parent := value.NewJSONValue()
		err := parser.parseObject(&parent)
		if err != nil {
			return value.NewJSONValue(), err
		}
		return parent, nil
	}
	if firstToken.IsEqualTo(token.NewTokenBeginArray()) {
		parent := value.NewJSONValue()
		err := parser.parseArray(&parent)
		if err != nil {
			return value.NewJSONValue(), err
		}
		return parent, nil
	}
	return value.NewJSONValue(), fmt.Errorf("Invalid JSON")
}