Beispiel #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
}
Beispiel #2
0
func (parser *Parser) parseObject(parent *value.JSONValue) error {
	parent.ObjectValue = make(map[string]value.JSONValue)

	firstToken, err := parser.tokenizer.NextToken()
	if err != nil {
		return err
	}
	if !firstToken.IsEqualTo(token.NewTokenBeginObject()) {
		return fmt.Errorf("JSON Object must start wit '{'")
	}

	for {
		nextToken, err := parser.tokenizer.PeekToken(0)
		if err != nil {
			return err
		}
		// End Of Object.
		if nextToken.IsEqualTo(token.NewTokenEndObject()) {
			parser.tokenizer.NextToken()
			break
		}
		// String Token must be key of object.
		if nextToken.IsSameKindTo(token.NewTokenString()) {
			parser.tokenizer.NextToken()

			mustbeSeparator, err := parser.tokenizer.NextToken()
			if err != nil {
				return err
			}
			if !mustbeSeparator.IsEqualTo(token.NewTokenSeparator()) {
				return fmt.Errorf("Object KeyValue Separator not found, %#v", mustbeSeparator)
			}

			currentValue := value.NewJSONValue()
			err = parser.parseValue(&currentValue)
			if err != nil {
				return err
			}
			parent.ObjectValue[nextToken.Value] = currentValue

			// If comma exists after value of object,
			// continuous token must be string which is key of the object too.
			maybeComma, err := parser.tokenizer.PeekToken(0)
			if err == nil && maybeComma.IsEqualTo(token.NewTokenComma()) {
				parser.tokenizer.NextToken()
				continue
			}
			break
		}
		return fmt.Errorf("Invalid JSON. Object is wrong")
	}
	return nil
}